﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Globalization;
using System.Threading;
using DevExpress.XtraSplashScreen;
using DevExpress.XtraBars.Helpers;
using DevExpress.XtraBars;
using FolderBrowserDlg;
using NetDiskPRJ.Common;
using DevExpress.Utils;
using DevExpress.XtraEditors.Controls;
using NetDiskPRJ.Base;
using System.Reflection;
using System.IO;
using System.Xml;
using System.Runtime.InteropServices;
using System.Drawing.Drawing2D;
using Newtonsoft.Json;
using DevExpress.XtraTreeList.Nodes;
using DevExpress.XtraTreeList;
using Newtonsoft.Json.Linq;
using NetDiskPRJ.NetDisk;
using System.Text.RegularExpressions;
using System.Collections;

namespace NetDiskPRJ
{
    public partial class MainForm : GridChildForm
    {
        string jsonMsg = "";
        string code = "";
        string msg = "";
     public static   ManualResetEvent mre;
     public static ManualResetEvent mre2;
        string showMode = "list";//显示模式：list列表模式，pic图片模式
        decimal RootFID = 0;//用户的根节点
        decimal CurrentFID = 0;//当前所在的文件夹编号
        int uploadStep = 0;//上传进度
        string uploadError = "";//上传时的错误
        int downloadStep = 0;//下载进度
        List<string> uploadingSameFileList = new List<string>();//服务器同文件夹下具有相同文件名的文件
        List<string> uploadingSameDirList = new List<string>(); //服务器同文件夹下具有相同文件名的文件夹
        List<string> uploadingSameFileCoverList = new List<string>();//服务器同文件夹下具有相同文件名的文件(需要覆盖)
        List<UploadFileClient> uploadpaths = new List<UploadFileClient>();
        string copyFIDs = "";//用于复制粘贴
        string cutFIDs = "";//用于剪切粘贴
        List<string> NotCoverPath = new List<string>();
        //悬浮窗口
        private FloatForm myTopMost;
        private Hashtable tempWatchers;
        private static string downloaddestpath = "";
        string prjWhere = "";
        string prjOrderField = " FType,FID ";
        Dictionary<string, string> DicColumnOrder = new Dictionary<string, string>();


        List<Model.NetDisk> uploadingList = new List<Model.NetDisk>();//正在上传
        List<Model.NetDisk> downloadingList = new List<Model.NetDisk>();//正在下载
        public MainForm()
        {
            InitializeComponent();
        }

        #region 打开窗口相关

        private Dictionary<string, string> dicFrmMenuName = new Dictionary<string, string>();
        /// <summary>
        /// 当前点击菜单名
        /// </summary>
        private string CurrentMnuName = "";
        /// <summary>
        /// 打开子窗体
        /// <creator>zhongyl</creator>
        /// <date>2011-12-17</date>
        /// </summary>
        /// <param name="ChildTypeString"></param>
        private void OpenWindow(string childTypeString, string mnuName, bool isChildClose = false, Model.CommonDlgParameters CommDlgParaModel = null)
        {
            base.OpenWaitForm(this.Handle);
            CurrentMnuName = mnuName;
            Form myChild = null;
            try
            {
                object[] objParams = null;
                if (CommDlgParaModel != null)
                {
                    objParams = new object[] { CommDlgParaModel };
                }

                if (isChildClose)
                {
                    foreach (Form f in this.MdiChildren)
                    {
                        if (f.GetType().ToString() == childTypeString)
                        {
                            f.Close();
                            break;
                        }
                    }
                }

                if (!ContainMDIChild(childTypeString))
                {
                    Assembly assembly = Assembly.GetExecutingAssembly();
                    Type typForm = assembly.GetType(childTypeString);
                    Object obj = typForm.InvokeMember(
                        null,
                        BindingFlags.DeclaredOnly |
                        BindingFlags.Public | BindingFlags.NonPublic |
                        BindingFlags.Instance | BindingFlags.CreateInstance,
                        null,
                        null,
                        objParams
                        );
                    if (obj != null)
                    {
                        myChild = obj as Form;

                        if (!dicFrmMenuName.ContainsKey(myChild.Name))
                        {
                            dicFrmMenuName.Add(myChild.Name, mnuName);
                        }
                        myChild.MdiParent = this;
                        MdiClient client = myChild.Parent as MdiClient;
                        myChild.Size = client.ClientSize;

                        myChild.Show();
                        myChild.Focus();
                        myChild.Location = new Point(0, 0);
                    }
                }
            }
            finally
            {
                base.CloseWaitForm();
            }
        }

        /// <summary>
        /// 查找子窗体
        /// <creator>zhongyl</creator>
        /// <date>2011-12-17</date>
        /// </summary>
        /// <param name="ChildTypeString"></param>
        /// <returns></returns>
        private bool ContainMDIChild(string childTypeString)
        {
            Form myMDIChild = null;
            foreach (Form f in this.MdiChildren)
            {
                if (f.GetType().ToString() == childTypeString)
                {
                    myMDIChild = f;
                    break;
                }
            }
            if (myMDIChild != null)
            {
                myMDIChild.TopMost = true;
                myMDIChild.Show();
                myMDIChild.Focus();
                return true;
            }
            else
                return false;
        }


        /// <summary>
        /// <creator>zhongyl</creator>
        /// <date>2011-12-17</date>
        /// </summary>
        /// <param name="childTypeString"></param>
        private void OpenDialogWindow(string childTypeString, string mnuName, Model.CommonDlgParameters CommonDlgParametersModel = null)
        {
            base.OpenWaitForm(this.Handle);
            object[] objParams = null;
            if (CommonDlgParametersModel != null)
            {
                objParams = new object[] { CommonDlgParametersModel };
            }
            Form myChild = null;
            try
            {
                Assembly assembly = Assembly.GetExecutingAssembly();
                Type typForm = assembly.GetType(childTypeString);
                Object obj = typForm.InvokeMember(
                       null,
                       BindingFlags.DeclaredOnly |
                       BindingFlags.Public | BindingFlags.NonPublic |
                       BindingFlags.Instance | BindingFlags.CreateInstance,
                       null,
                       null,
                       objParams);
                if (obj != null)
                {
                    myChild = obj as Form;
                    CurrentMnuName = mnuName;
                    Image image = base.GetMenuImageCollection().Images[CurrentMnuName];
                    if (image != null)
                    {
                        Bitmap bt = (Bitmap)image;
                        myChild.Icon = Icon.FromHandle(bt.GetHicon());
                    }
                    else
                    {
                        myChild.Icon = this.Icon;
                    }
                    myChild.Owner = this;
                    myChild.ShowDialog();
                }
            }
            finally
            {
                base.CloseWaitForm();

            }
        }

        private void loginNetdisk()
        {
            try
            {
                LoginForm frmLogin = new LoginForm();
                DialogResult dr = frmLogin.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    //this.WindowState = FormWindowState.Maximized;
                    //登陆后 初始文件夹
                    jsonMsg = Base.GlobalParams.NetDiskServiceSVC.InitMyDirs();
                    Common.GlobalUtil.GetJsonMsgResult(jsonMsg, out code, out msg);
                    if (code != "0")
                    {
                        XtraMessageBox.Show(msg, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        InitPage();
                        LoadMainMenu();
                        //
                    }

                    //显示用户
                    barlblLogID.Caption = Base.GlobalParams.GLOBAL_LOGFULLNAME;

                    CurrentFID = RootFID;
                    RefreshNetDisk();

                }
                else
                {
                    ExitApplication();
                }
            }
            catch (Exception ee)
            {
                XtraMessageBox.Show(ee.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                ExitApplication();
            }
        }


        private void InitPage()
        {
            timerUpload.Enabled = false;
            timerDownload.Enabled = false;
            this.notifyIcon1.Icon = this.Icon;//托盘图标
            if (!this.DesignMode)
            {
                //地址栏
                AddAddrBarItem();

                //ribbon
                InitRibbon();
            }

            InitListView();//初始化listview
            lvBindDataByID(prjOrderField);//绑定listview数据
            StatusBarShowChange();//状态栏文字改变
            InitOrderField();//初始化排序字段
            gvUploadInit();//初始化上传列表
            gvDownloadInit();//初始化下载列表

            //初始化时隐藏传输列表
            dockPnlLoad.Visibility = DevExpress.XtraBars.Docking.DockVisibility.Hidden;
            ResetProgressUploading();//重置正在上传进度条
            ResetProgressDownloading();//重置正在下载进度条

            // 创建浮动窗口
            myTopMost = new FloatForm(this);
            myTopMost.Show();
            InitCntOpenFloatForm();//修改显示/隐藏悬浮窗
            this.Text = base.AssemblyTitle;

        }

        #endregion

        #region 左边树菜单

        /// <summary>
        /// 树形列表图片集
        /// </summary>
        private ImageCollection TreeImage = new ImageCollection();

        /// <summary>
        /// 加载界面上的主菜单
        /// <creator>zhongyl</creator>
        /// <date>2011-12-16</date>
        /// </summary>
        private void LoadMainMenu()
        {
            //左边树形菜单
            tlstLeft.BeginUpdate();
            tlstLeft.Columns.Add();
            tlstLeft.Columns[0].Caption = "文件列表";
            tlstLeft.Columns[0].VisibleIndex = 0;
            tlstLeft.Columns.Add();

            TreeImage = base.GetFormImageCollection();
            tlstLeft.StateImageList = TreeImage;
            tlstLeft.OptionsBehavior.ShowToolTips = false;
            //tlstLeft.Painter.IndicatorImages.editorIsInactiveIndicatorImageIndex = -1; 
            tlstLeft.EndUpdate();

            BindLeftTree();


        }

        private void BindLeftTree()
        {
            tlstLeft.BeginUpdate();

            tlstLeft.Nodes.Clear();

            string strJson = Base.GlobalParams.NetDiskServiceSVC.GetDirByLogID(Base.GlobalParams.GLOBAL_LOGID);
            List<Model.NetDisk> dirList = JsonConvert.DeserializeObject<List<Model.NetDisk>>(strJson);

            if (dirList.Count > 0)
            {
                List<Model.NetDisk> dirFirstList = (from m in dirList
                                                    where m.FParentID == null
                                                    select m).ToList();
                foreach (Model.NetDisk dirModel in dirFirstList)
                {

                    //添加节点
                    TreeListNode rootNode = tlstLeft.AppendNode(
                                new object[] { "我的云盘" },
                                null);
                    rootNode.Tag = dirModel.FID;
                    RootFID = dirModel.FID;//根节点赋值
                    //父节点为null的即当前用户的根目录，有且只有一个。
                    if (CurrentFID == 0)//默认为为目录
                    {
                        CurrentFID = dirFirstList[0].FID;
                        tlstLeft.FocusedNode = rootNode;
                    }
                    else
                    {
                        //设置选中节点
                        if (decimal.Parse(rootNode.Tag.ToString()) == CurrentFID)
                        {
                            tlstLeft.FocusedNode = rootNode;
                        }
                    }
                    //重置路径
                    currentindex = 1;
                    this.ReturnFolder.Clear();
                    bbgp.ClearLinks();
                    BarCheckItem citm = new BarCheckItem();

                    citm.Caption = "我的云盘";
                    citm.RibbonStyle = DevExpress.XtraBars.Ribbon.RibbonItemStyles.SmallWithText;
                    citm.PaintStyle = BarItemPaintStyle.CaptionGlyph;
                    int imgidx = base.GetImageIndex("home_highlight", imgCollectToolBar);
                    citm.ImageIndex = imgidx;
                    citm.Id = barMainManager.GetNewItemId();
                    citm.Tag = CurrentFID.ToString();

                    bbgp.AddItem(citm);
                    CheckArrowBar();

                    this.ReturnFolder.Add(rootNode);
                    //子菜单
                    List<Model.NetDisk> tmpDirList = (from m in dirList
                                                      where m.FParentID == dirModel.FID
                                                      select m).ToList();
                    if (tmpDirList.Count > 0)
                    {
                        GetChildDirList(tmpDirList, rootNode, dirList);
                    }
                    rootNode.StateImageIndex = GetImageIndex("NetDiskPRJ_small", TreeImage);
                    rootNode.Expanded = true;
                }
            }

            tlstLeft.EndUpdate();
        }

        /// <summary>
        /// 获取子文件夹
        /// </summary>
        /// <param name="dirChildList"></param>
        /// <param name="parentNode"></param>
        /// <param name="dirList"></param>
        public void GetChildDirList(List<Model.NetDisk> dirChildList, TreeListNode parentNode, List<Model.NetDisk> dirList)
        {
            foreach (Model.NetDisk dirModel in dirChildList)
            {
                //添加节点
                TreeListNode node = tlstLeft.AppendNode(
                            new object[] { dirModel.FName },
                            parentNode);
                node.Tag = dirModel.FID;

                //设置选中节点
                if (decimal.Parse(node.Tag.ToString()) == CurrentFID)
                {
                    tlstLeft.FocusedNode = node;
                }

                //子菜单
                List<Model.NetDisk> tmpDirList = (from m in dirList
                                                  where m.FParentID == dirModel.FID
                                                  select m).ToList();

                if (tmpDirList.Count > 0)
                {
                    GetChildDirList(tmpDirList, node, dirList);
                }
                node.StateImageIndex = GetImageIndex("folder_close", TreeImage);
                node.Expanded = true;
            }
        }

        private void tlstLeft_AfterExpand(object sender, NodeEventArgs e)
        {
            if (e.Node.Tag.ToString() != RootFID.ToString())
            {
                e.Node.StateImageIndex = GetImageIndex("folder_open", TreeImage);
            }
        }

        private void tlstLeft_AfterCollapse(object sender, NodeEventArgs e)
        {
            if (e.Node.Tag.ToString() != RootFID.ToString())
            {
                e.Node.StateImageIndex = GetImageIndex("folder_close", TreeImage);
            }
        }

        private void tlstLeft_FocusedNodeChanged(object sender, FocusedNodeChangedEventArgs e)
        {
            if (e.Node != null)
            {
                if (e.Node.Tag != null)
                {

                    string FID = e.Node.Tag.ToString();

                    CurrentFID = decimal.Parse(e.Node.Tag.ToString());
                    //判断当前文件夹是否存在，如果不在，则刷新
                    string JsonNetDiskModel = "";
                    string jsonMsg = Base.GlobalParams.NetDiskServiceSVC.GetNetDisk(FID);
                    Common.GlobalUtil.GetJsonMsgResult(jsonMsg, out code, out msg);
                    if (code != "0")
                    {
                        XtraMessageBox.Show(msg, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    else
                    {
                        JObject msgObj = JObject.Parse(JObject.Parse(jsonMsg)["msg"].ToString());
                        JsonNetDiskModel = msgObj["JsonNetDiskModel"].ToString();
                        if (JsonNetDiskModel == "")
                        {
                            CurrentFID = RootFID;
                            RefreshNetDisk();
                            XtraMessageBox.Show("不存在当前文件夹", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        else
                        {
                            currentindex += 1;
                            if (this.ReturnFolder.Count < currentindex)
                            {
                                this.ReturnFolder.Add(e.Node);
                            }
                            else
                            {
                                this.ReturnFolder[currentindex - 1] = e.Node;
                            }
                            RefreshAddrBar(FID);
                        }
                    }

                }
            }

        }
        #endregion

        #region 右边数据显示相关
        private void InitListView()
        {
            lvFile.View = System.Windows.Forms.View.Details;           //将view属性设为Details。
            //listView1.LabelEdit = true;              //允许用户编辑文本项。
            lvFile.AllowColumnReorder = true;     //允许用户重排列。
            lvFile.CheckBoxes = false;            //显示check boxes。
            lvFile.FullRowSelect = true;          //允许选择项及其子项。
            //listView1.GridLines = true;              //显示行列的网格线。
            //listView1.Sorting = SortOrder.Ascending;   //所列项按升序自动排序。

            //产生项和子项的列，Add方法往列添加3个参数：列表头，初始宽度，对齐方式。
            lvFile.Columns.Add("FName", "文件名", 250, HorizontalAlignment.Left, 1000);
            lvFile.Columns.Add("FSize", "大小", 100, HorizontalAlignment.Right, 1000);
            lvFile.Columns.Add("FDate", "修改日期", 100, HorizontalAlignment.Right, 1000);

            ImageList lvLargeImgList = new ImageList();
            lvLargeImgList.ImageSize = new Size(133, 104);
            foreach (Image img in imgCollectListview.Images)
            {
                lvLargeImgList.Images.Add(img);
            }
            lvFile.LargeImageList = lvLargeImgList;

            ImageList lvSmallImgList = new ImageList();
            lvSmallImgList.ImageSize = new Size(16, 16);
            foreach (Image img in imgCollectListview.Images)
            {
                lvSmallImgList.Images.Add(img);
            }
            lvFile.SmallImageList = lvSmallImgList;
        }

        private void lvBindDataByWhere(string strWhere, string orderField = " FType,FID ")
        {
            string jsonNetDiskList = Base.GlobalParams.NetDiskServiceSVC.GetListCTE(RootFID.ToString(), strWhere, orderField);
            List<Model.NetDisk> netDiskList = JsonConvert.DeserializeObject<List<Model.NetDisk>>(jsonNetDiskList);
            BindData(netDiskList);
        }

        /// <summary>
        /// 根据CurrentFID绑定数据
        /// </summary>
        private void lvBindDataByID(string orderField = " FType,FID ")
        {
            string FID = CurrentFID.ToString();
            prjWhere = "";

            string jsonNetDiskList = Base.GlobalParams.NetDiskServiceSVC.GetList(FID, orderField);
            List<Model.NetDisk> netDiskList = JsonConvert.DeserializeObject<List<Model.NetDisk>>(jsonNetDiskList);


            BindData(netDiskList);
        }

        /// <summary>
        /// 绑定数据
        /// </summary>
        private void BindData(List<Model.NetDisk> netDiskList)
        {
            lvFile.Items.Clear();

            //添加头
            foreach (Model.NetDisk netDiskModel in netDiskList)
            {
                ListViewItem item = new ListViewItem(netDiskModel.FName, GetListViewImage(netDiskModel.FSuffixName, showMode, netDiskModel.FType));
                item.Name = "FName";
                ListViewItem.ListViewSubItem subItem = new ListViewItem.ListViewSubItem();
                if (netDiskModel.FType == "D")
                {
                    subItem = new ListViewItem.ListViewSubItem(item, "");
                }
                else
                {
                    subItem = new ListViewItem.ListViewSubItem(item, GetstrSize(netDiskModel.FSize));
                }
                subItem.Name = "FSize";
                item.SubItems.Add(subItem);
                subItem = new ListViewItem.ListViewSubItem(item, netDiskModel.FDate.ToString("yyyy-MM-dd"));
                subItem.Name = "FDate";
                item.SubItems.Add(subItem);
                subItem = new ListViewItem.ListViewSubItem(item, netDiskModel.FID.ToString("n0").Replace(",", ""));
                subItem.Name = "FID";
                item.SubItems.Add(subItem);
                subItem = new ListViewItem.ListViewSubItem(item, netDiskModel.FType);
                subItem.Name = "FType";
                item.SubItems.Add(subItem);
                //添加后缀
                item.Tag = netDiskModel.FSuffixName;
                //item.SubItems.Add(netDiskModel.FSize.ToString());
                //item.SubItems.Add(netDiskModel.FDate.ToString("yyyy-MM-dd"));
                //item.SubItems.Add(netDiskModel.FID.ToString());
                lvFile.Items.Add(item);
            }


        }

        /// <summary>
        /// 获取图标
        /// </summary>
        /// <param name="FSufixName">后缀名</param>
        /// <param name="showMode">显示模式</param>
        /// <param name="FType">文件/文件夹</param>
        /// <returns></returns>
        private int GetListViewImage(string FSufixName, string showMode, string FType)
        {
            if (showMode == "pic")
            {
                if (FType == "F")//文件
                {
                    switch (FSufixName)
                    {
                        case "doc":
                            return base.GetImageIndex("bImg_DocType", imgCollectListview);
                        case "docx":
                            return base.GetImageIndex("bImg_DocType", imgCollectListview);
                        case "avi":
                            return base.GetImageIndex("bImg_VideoType", imgCollectListview);
                        case "jpg":
                            return base.GetImageIndex("bImg_ImgType", imgCollectListview);
                        case "jpeg":
                            return base.GetImageIndex("bImg_ImgType", imgCollectListview);
                        case "gif":
                            return base.GetImageIndex("bImg_ImgType", imgCollectListview);
                        case "png":
                            return base.GetImageIndex("bImg_ImgType", imgCollectListview);
                        case "bmp":
                            return base.GetImageIndex("bImg_ImgType", imgCollectListview);
                        case "exe":
                            return base.GetImageIndex("bImg_ExeType", imgCollectListview);
                        case "rar":
                            return base.GetImageIndex("bImg_RarType", imgCollectListview);
                        case "zip":
                            return base.GetImageIndex("bImg_RarType", imgCollectListview);
                        case "pdf":
                            return base.GetImageIndex("bImg_PdfType", imgCollectListview);
                        case "ppt":
                            return base.GetImageIndex("bImg_PptType", imgCollectListview);
                        case "pptx":
                            return base.GetImageIndex("bImg_PptType", imgCollectListview);
                        case "txt":
                            return base.GetImageIndex("bImg_TxtType", imgCollectListview);

                        case "mp3":
                            return base.GetImageIndex("bImg_MusicType", imgCollectListview);
                        case "xls":
                            return base.GetImageIndex("bImg_XlsType", imgCollectListview);
                        case "xlsx":
                            return base.GetImageIndex("bImg_XlsType", imgCollectListview);
                        default:
                            return base.GetImageIndex("bImg_OtherType", imgCollectListview);
                    }
                }
                else//文件夹
                {
                    return base.GetImageIndex("bImg_FolderType", imgCollectListview);
                }
            }
            else
            {
                if (FType == "F")//文件
                {
                    switch (FSufixName)
                    {
                        case "doc":
                            return base.GetImageIndex("sImg_DocType", imgCollectListview);
                        case "docx":
                            return base.GetImageIndex("sImg_DocType", imgCollectListview);
                        case "avi":
                            return base.GetImageIndex("sImg_VideoType", imgCollectListview);
                        case "jpg":
                            return base.GetImageIndex("sImg_ImgType", imgCollectListview);
                        case "jpeg":
                            return base.GetImageIndex("sImg_ImgType", imgCollectListview);
                        case "gif":
                            return base.GetImageIndex("sImg_ImgType", imgCollectListview);
                        case "png":
                            return base.GetImageIndex("sImg_ImgType", imgCollectListview);
                        case "bmp":
                            return base.GetImageIndex("sImg_ImgType", imgCollectListview);
                        case "exe":
                            return base.GetImageIndex("sImg_ExeType", imgCollectListview);
                        case "rar":
                            return base.GetImageIndex("sImg_RarType", imgCollectListview);
                        case "zip":
                            return base.GetImageIndex("sImg_RarType", imgCollectListview);
                        case "pdf":
                            return base.GetImageIndex("sImg_PdfType", imgCollectListview);
                        case "mp3":
                            return base.GetImageIndex("sImg_MusicType", imgCollectListview);
                        case "ppt":
                            return base.GetImageIndex("sImg_PptType", imgCollectListview);
                        case "pptx":
                            return base.GetImageIndex("sImg_PptType", imgCollectListview);
                        case "txt":
                            return base.GetImageIndex("sImg_TxtType", imgCollectListview);
                        case "xls":
                            return base.GetImageIndex("sImg_XlsType", imgCollectListview);
                        case "xlsx":
                            return base.GetImageIndex("sImg_XlsType", imgCollectListview);
                        default:
                            return base.GetImageIndex("sImg_OtherType", imgCollectListview);
                    }
                }
                else//文件夹
                {
                    return base.GetImageIndex("sImg_FolderType", imgCollectListview);
                }
            }
        }

        /// <summary>
        /// 修改成有单位的文件大小
        /// </summary>
        /// <param name="size"></param>
        /// <returns></returns>
        private string GetstrSize(decimal size)
        {
            string strSize = "0KB";
            if (size == 0)
            {
                strSize = "0B";
            }
            else if (size > 0 && size < 1024)
            {
                size = Math.Round(size, 0);
                string _size = size.ToString();
                strSize = _size.ToString() + "B";
            }
            else if (size > 0 && size < 1048576)
            {
                string _size = ((decimal)size / (decimal)1024).ToString("0.00");
                strSize = _size.ToString() + "KB";
            }
            else if (size >= 1048576 && size < 1073741824)
            {
                string _size = ((decimal)size / (decimal)1048576).ToString("0.00");
                strSize = _size + "MB";
            }
            else
            {
                string _size = ((decimal)size / (decimal)1073741824).ToString("0.00");
                strSize = _size + "GB";
            }
            return strSize;
        }


        /// <summary>
        /// 选项选中状态改变时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lvFile_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            StatusBarShowChange();
        }
        /// <summary>
        /// 状态栏文字改变
        /// </summary>
        private void StatusBarShowChange()
        {
            if (lvFile.SelectedItems.Count > 0)
            {
                barlblCount.Caption = "已选中" + lvFile.SelectedItems.Count + "个文件/文件夹";
            }
            else
            {
                barlblCount.Caption = lvFile.Items.Count + "项";
            }
        }
        /// <summary>
        /// 排序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lvFile_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            //更改排序
            prjOrderField = "";
            string columnName = lvFile.Columns[e.Column].Name;
            switch (columnName)
            {
                case "FName":
                    if (DicColumnOrder["FName"] != "FName")
                    {
                        DicColumnOrder["FName"] = "FName";
                    }
                    else
                    {
                        DicColumnOrder["FName"] = "FName desc";
                    }
                    break;
                case "FSize":
                    if (DicColumnOrder["FSize"] != "FSize")
                    {
                        DicColumnOrder["FSize"] = "FSize";
                    }
                    else
                    {
                        DicColumnOrder["FSize"] = "FSize desc";
                    }
                    break;
                case "FDate":
                    if (DicColumnOrder["FDate"] != "FDate")
                    {
                        DicColumnOrder["FDate"] = "FDate";
                    }
                    else
                    {
                        DicColumnOrder["FDate"] = "FDate desc";
                    }
                    break;
            }

            //先添加当前点击的字段
            foreach (KeyValuePair<string, string> item in DicColumnOrder)
            {
                if (columnName == item.Key)
                {
                    if (item.Value != "")
                    {
                        prjOrderField += item.Value + ",";
                    }
                }
            }

            //再添加未点击的字段
            foreach (KeyValuePair<string, string> item in DicColumnOrder)
            {
                if (columnName != item.Key)
                {
                    if (item.Value != "")
                    {
                        prjOrderField += item.Value + ",";
                    }
                }
            }

            prjOrderField = prjOrderField.Trim(',');
            if (prjWhere == "")
            {
                lvBindDataByID(prjOrderField);
            }
            else
            {
                lvBindDataByWhere(prjWhere, prjOrderField);
            }

        }

        #endregion

        #region Ribbon相关

        /// <summary>
        /// 根据item名获取item
        /// </summary>
        /// <param name="buttonName"></param>
        /// <returns></returns>
        private BarItem GetRibbonBarItemByName(string buttonName)
        {
            BarItem bi = null;
            for (int i = 0; i < ribbonNetdisk.Items.Count; i++)
            {
                if (ribbonNetdisk.Items[i].Name == buttonName)
                {
                    bi = ribbonNetdisk.Items[i];
                    break;
                }

            }
            return bi;
        }

        private void InitRibbon()
        {
            #region 操作
            #region 操作

            BarButtonItem barButtonItem = new BarButtonItem();
            barButtonItem.Caption = "上传";
            barButtonItem.Name = "upload";
            barButtonItem.RibbonStyle = DevExpress.XtraBars.Ribbon.RibbonItemStyles.All;
            barButtonItem.PaintStyle = BarItemPaintStyle.CaptionGlyph;
            barButtonItem.LargeImageIndex = base.GetImageIndex("button_upload", imgLargeCollectToolBar);
            barButtonItem.ItemClick += new ItemClickEventHandler(ButtonUpload);
            rbnGrpEdit.ItemLinks.Add(barButtonItem);

            barButtonItem = new BarButtonItem();
            barButtonItem.Caption = "下载";
            barButtonItem.Name = "download";
            barButtonItem.RibbonStyle = DevExpress.XtraBars.Ribbon.RibbonItemStyles.All;
            barButtonItem.PaintStyle = BarItemPaintStyle.CaptionGlyph;
            barButtonItem.LargeImageIndex = base.GetImageIndex("button_downLoad", imgLargeCollectToolBar);
            barButtonItem.ItemClick += new ItemClickEventHandler(ButtonDownLoad);
            rbnGrpEdit.ItemLinks.Add(barButtonItem);

            barButtonItem = new BarButtonItem();
            barButtonItem.Caption = "删除";
            barButtonItem.Name = "delete";
            barButtonItem.RibbonStyle = DevExpress.XtraBars.Ribbon.RibbonItemStyles.All;
            barButtonItem.PaintStyle = BarItemPaintStyle.CaptionGlyph;
            barButtonItem.LargeImageIndex = base.GetImageIndex("button_delete", imgLargeCollectToolBar);
            barButtonItem.ItemClick += new ItemClickEventHandler(ButtonDelete);
            rbnGrpEdit.ItemLinks.Add(barButtonItem);

            barButtonItem = new BarButtonItem();
            barButtonItem.Caption = "新建文件夹";
            barButtonItem.Name = "crateDir";
            barButtonItem.RibbonStyle = DevExpress.XtraBars.Ribbon.RibbonItemStyles.All;
            barButtonItem.PaintStyle = BarItemPaintStyle.CaptionGlyph;
            barButtonItem.LargeImageIndex = base.GetImageIndex("button_createDir", imgLargeCollectToolBar);
            barButtonItem.ItemClick += new ItemClickEventHandler(ButtonCreateDir);
            rbnGrpEdit.ItemLinks.Add(barButtonItem);

            barButtonItem = new BarButtonItem();
            barButtonItem.Caption = "重命名";
            barButtonItem.Name = "rename";
            barButtonItem.RibbonStyle = DevExpress.XtraBars.Ribbon.RibbonItemStyles.All;
            barButtonItem.PaintStyle = BarItemPaintStyle.CaptionGlyph;
            barButtonItem.LargeImageIndex = base.GetImageIndex("button_reName", imgLargeCollectToolBar);
            barButtonItem.ItemClick += new ItemClickEventHandler(ButtonReName);
            rbnGrpEdit.ItemLinks.Add(barButtonItem);

            barButtonItem = new BarButtonItem();
            barButtonItem.Caption = "移动";
            barButtonItem.Name = "move";
            barButtonItem.RibbonStyle = DevExpress.XtraBars.Ribbon.RibbonItemStyles.All;
            barButtonItem.PaintStyle = BarItemPaintStyle.CaptionGlyph;
            barButtonItem.LargeImageIndex = base.GetImageIndex("button_move", imgLargeCollectToolBar);
            barButtonItem.ItemClick += new ItemClickEventHandler(ButtonMove);
            rbnGrpEdit.ItemLinks.Add(barButtonItem);

            barButtonItem = new BarButtonItem();
            barButtonItem.Caption = "复制到";
            barButtonItem.Name = "copy";
            barButtonItem.RibbonStyle = DevExpress.XtraBars.Ribbon.RibbonItemStyles.All;
            barButtonItem.PaintStyle = BarItemPaintStyle.CaptionGlyph;
            barButtonItem.LargeImageIndex = base.GetImageIndex("button_copy", imgLargeCollectToolBar);
            barButtonItem.ItemClick += new ItemClickEventHandler(ButtonCopy);
            rbnGrpEdit.ItemLinks.Add(barButtonItem);


            #endregion

            #region 选择

            barButtonItem = new BarButtonItem();
            barButtonItem.Caption = "全部选中";
            barButtonItem.Name = "selectRowAll";
            barButtonItem.RibbonStyle = DevExpress.XtraBars.Ribbon.RibbonItemStyles.SmallWithText;
            barButtonItem.PaintStyle = BarItemPaintStyle.CaptionGlyph;
            barButtonItem.ImageIndex = base.GetImageIndex("button_selectrowall", imgCollectToolBar);
            barButtonItem.ItemClick += new ItemClickEventHandler(ButtonSelectRowAll);
            rbnGrpchoose.ItemLinks.Add(barButtonItem);

            barButtonItem = new BarButtonItem();
            barButtonItem.Caption = "全部反选";
            barButtonItem.Name = "inverseSelectRowAll";
            barButtonItem.RibbonStyle = DevExpress.XtraBars.Ribbon.RibbonItemStyles.SmallWithText;
            barButtonItem.PaintStyle = BarItemPaintStyle.CaptionGlyph;
            barButtonItem.ImageIndex = base.GetImageIndex("button_inverseselectrowall", imgCollectToolBar);
            barButtonItem.ItemClick += new ItemClickEventHandler(ButtonInverseSelectRowAll);
            rbnGrpchoose.ItemLinks.Add(barButtonItem);

            barButtonItem = new BarButtonItem();
            barButtonItem.Caption = "取消选中";
            barButtonItem.Name = "unSelectRow";
            barButtonItem.RibbonStyle = DevExpress.XtraBars.Ribbon.RibbonItemStyles.SmallWithText;
            barButtonItem.PaintStyle = BarItemPaintStyle.CaptionGlyph;
            barButtonItem.ImageIndex = base.GetImageIndex("button_unselectrow", imgCollectToolBar);
            barButtonItem.ItemClick += new ItemClickEventHandler(ButtonUnselectRow);
            rbnGrpchoose.ItemLinks.Add(barButtonItem);





            #endregion

            #region 查看

            BarCheckItem barCheckItem = new BarCheckItem();
            barCheckItem.Checked = false;
            barCheckItem.Caption = "传输列表";
            barCheckItem.Name = "loadbar";
            barCheckItem.RibbonStyle = DevExpress.XtraBars.Ribbon.RibbonItemStyles.All;
            barCheckItem.PaintStyle = BarItemPaintStyle.CaptionGlyph;
            barCheckItem.LargeImageIndex = base.GetImageIndex("button_loadbar", imgLargeCollectToolBar);
            barCheckItem.ItemClick += new ItemClickEventHandler(ButtonLoadBar);
            rbnGrpShow.ItemLinks.Add(barCheckItem);

            #endregion

            #region 设置
            barButtonItem = new BarButtonItem();
            barButtonItem.Caption = "设置";
            barButtonItem.Name = "upset";
            barButtonItem.RibbonStyle = DevExpress.XtraBars.Ribbon.RibbonItemStyles.All;
            barButtonItem.PaintStyle = BarItemPaintStyle.CaptionGlyph;
            barButtonItem.LargeImageIndex = base.GetImageIndex("button_upset", imgLargeCollectToolBar);
            barButtonItem.ItemClick += new ItemClickEventHandler(ButtonUpset);
            rbnGrpUpset.ItemLinks.Add(barButtonItem);
            #endregion


            #region 退出
            barButtonItem = new BarButtonItem();
            barButtonItem.Caption = "注销";
            barButtonItem.Name = "zhuxiao";
            barButtonItem.RibbonStyle = DevExpress.XtraBars.Ribbon.RibbonItemStyles.All;
            barButtonItem.PaintStyle = BarItemPaintStyle.CaptionGlyph;
            barButtonItem.LargeImageIndex = base.GetImageIndex("logout.png", imgLargeCollectToolBar);
            barButtonItem.ItemClick += new ItemClickEventHandler(barButtonItem_ItemClick);
            rbnGrpLogout.ItemLinks.Add(barButtonItem);



            barButtonItem = new BarButtonItem();
            barButtonItem.Caption = "退出";
            barButtonItem.Name = "logout";
            barButtonItem.RibbonStyle = DevExpress.XtraBars.Ribbon.RibbonItemStyles.All;
            barButtonItem.PaintStyle = BarItemPaintStyle.CaptionGlyph;
            barButtonItem.LargeImageIndex = base.GetImageIndex("button_logout", imgLargeCollectToolBar);
            barButtonItem.ItemClick += new ItemClickEventHandler(ButtonLogout);
            rbnGrpLogout.ItemLinks.Add(barButtonItem);
            #endregion

            #endregion

            #region 帮助

            barButtonItem = new BarButtonItem();
            barButtonItem.Caption = "帮助";
            barButtonItem.Name = "help";
            barButtonItem.RibbonStyle = DevExpress.XtraBars.Ribbon.RibbonItemStyles.All;
            barButtonItem.PaintStyle = BarItemPaintStyle.CaptionGlyph;
            barButtonItem.LargeImageIndex = base.GetImageIndex("button_help", imgLargeCollectToolBar);
            barButtonItem.ItemClick += new ItemClickEventHandler(ButtonHelp);
            rbnGrpHelp.ItemLinks.Add(barButtonItem);

            barButtonItem = new BarButtonItem();
            barButtonItem.Caption = "关于";
            barButtonItem.Name = "about";
            barButtonItem.RibbonStyle = DevExpress.XtraBars.Ribbon.RibbonItemStyles.All;
            barButtonItem.PaintStyle = BarItemPaintStyle.CaptionGlyph;
            barButtonItem.LargeImageIndex = base.GetImageIndex("button_about", imgLargeCollectToolBar);
            barButtonItem.ItemClick += new ItemClickEventHandler(ButtonAbout);
            rbnGrpHelp.ItemLinks.Add(barButtonItem);

            barButtonItem = new BarButtonItem();
            barButtonItem.Caption = "操作手册";
            barButtonItem.Name = "manual";
            barButtonItem.RibbonStyle = DevExpress.XtraBars.Ribbon.RibbonItemStyles.All;
            barButtonItem.PaintStyle = BarItemPaintStyle.CaptionGlyph;
            barButtonItem.LargeImageIndex = base.GetImageIndex("button_manual", imgLargeCollectToolBar);
            barButtonItem.ItemClick += new ItemClickEventHandler(ButtonManual);
            rbnGrpHelp.ItemLinks.Add(barButtonItem);

            #endregion

            #region 工具栏

            //barButtonItem = new BarButtonItem();
            //barButtonItem.Caption = "向后";
            //barButtonItem.Name = "backward";
            //barButtonItem.RibbonStyle = DevExpress.XtraBars.Ribbon.RibbonItemStyles.SmallWithoutText;
            //barButtonItem.PaintStyle = BarItemPaintStyle.CaptionGlyph;
            //barButtonItem.ImageIndex = base.GetImageIndex("back_hover", imgCollectToolBar);
            //barButtonItem.ImageIndexDisabled = base.GetImageIndex("back_disabled", imgCollectToolBar);
            //barButtonItem.ItemClick += new ItemClickEventHandler(ButtonBackward);
            //ribbonNetdisk.Toolbar.ItemLinks.Add(barButtonItem);

            //barButtonItem = new BarButtonItem();
            //barButtonItem.Caption = "向前";
            //barButtonItem.Name = "forward";
            //barButtonItem.RibbonStyle = DevExpress.XtraBars.Ribbon.RibbonItemStyles.SmallWithoutText;
            //barButtonItem.PaintStyle = BarItemPaintStyle.CaptionGlyph;
            //barButtonItem.ImageIndex = base.GetImageIndex("forward_hover", imgCollectToolBar);
            //barButtonItem.ImageIndexDisabled = base.GetImageIndex("forward_disabled", imgCollectToolBar);
            //barButtonItem.ItemClick += new ItemClickEventHandler(ButtonForward);
            //ribbonNetdisk.Toolbar.ItemLinks.Add(barButtonItem);

            ////地址
            //bbgp = new BarButtonGroup();
            //bbgp.Width = 500;
            //ribbonNetdisk.Toolbar.ItemLinks.Add(bbgp);

            ////搜索栏

            //DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit repositoryItemSearch = new DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit();
            //repositoryItemSearch.Buttons[0].Kind = ButtonPredefines.Glyph;
            //repositoryItemSearch.Buttons[0].Image = NetDiskPRJ.Properties.Resources.search_icon_hover;

            //repositoryItemSearch.ButtonClick += new ButtonPressedEventHandler(barButton_ItemClicksearch);
            //mnuSearch = new BarEditItem();
            //mnuSearch.Width = 200;
            //mnuSearch.Edit = repositoryItemSearch;
            //mnuSearch.EditValue = "";
            ////  mnuSearch.AutoFillWidth = true;
            //ribbonNetdisk.Toolbar.ItemLinks.Add(mnuSearch);

            //barButtonItem = new BarButtonItem();
            //barButtonItem.Caption = "显示文件夹";
            //barButtonItem.Name = "leftTree";
            //barButtonItem.RibbonStyle = DevExpress.XtraBars.Ribbon.RibbonItemStyles.SmallWithText;
            //barButtonItem.PaintStyle = BarItemPaintStyle.CaptionGlyph;
            //barButtonItem.ImageIndex = base.GetImageIndex("hide_leftsidebar_hover", imgCollectToolBar);
            //barButtonItem.ItemClick += new ItemClickEventHandler(ButtonLeftTree);
            //ribbonNetdisk.Toolbar.ItemLinks.Add(barButtonItem);

            //barButtonItem = new BarButtonItem();
            //barButtonItem.Caption = "切换查看模式";
            //barButtonItem.Name = "showMode";
            //barButtonItem.RibbonStyle = DevExpress.XtraBars.Ribbon.RibbonItemStyles.SmallWithText;
            //barButtonItem.PaintStyle = BarItemPaintStyle.CaptionGlyph;
            //barButtonItem.ImageIndex = base.GetImageIndex("Navigator_list_hover", imgCollectToolBar);
            //barButtonItem.ItemClick += new ItemClickEventHandler(ButtonShowMode);
            //ribbonNetdisk.Toolbar.ItemLinks.Add(barButtonItem);

            #endregion


        }
        /// <summary>
        /// 注销按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void barButtonItem_ItemClick(object sender, ItemClickEventArgs e)
        {
            Common.ConfigHelper.SeTconfigKeyValue("islogout", "Y");
            // Common.ConfigHelper.SeTconfigKeyValue("AutoLogin", "N");
            //throw new NotImplementedException();
            notifyIcon1.Dispose();
            Application.Restart();
        }
        #endregion

        /// <summary>
        /// 主窗口载入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_Load(object sender, EventArgs e)
        {

            XtraMessageBoxForm.ForceShortBox = true;//设置程序的提示框 自动换行




            CultureInfo culinfo = new CultureInfo("zh-CN");
            System.Globalization.DateTimeFormatInfo dinfo = (DateTimeFormatInfo)Thread.CurrentThread.CurrentCulture.DateTimeFormat.Clone(); //这个是只读的,所以先复制一份
            dinfo.ShortDatePattern = "yyyy-MM-dd";
            dinfo.LongDatePattern = "yyyy-MM-dd";
            dinfo.ShortTimePattern = "HH:mm";
            dinfo.LongTimePattern = "HH:mm:ss";
            culinfo.DateTimeFormat = dinfo;
            Thread.CurrentThread.CurrentCulture = culinfo; //只更改当前进程的日期格式

            Base.GlobalParams.GLOBAL_VERSION = base.AssemblyVersion;//版本
            SplashScreenManager.ShowForm(this, typeof(SplashScreenInitForm), false, false, false);//进度条
            SplashScreenManager.Default.SendCommand(SplashScreenInitForm.SplashScreenCommand.SetMessage, "正在装载系统,请耐心等待...");

            //默认皮肤
            string skinStyleName = Common.ConfigHelper.GetConfigString("SkinStyleName");
            if (skinStyleName != "")
            {
                DevExpress.LookAndFeel.UserLookAndFeel.Default.SetSkinStyle(skinStyleName);
            }
            string jsonMsg = "";
            try
            {
                jsonMsg = Base.GlobalParams.NetDiskServiceSVC.DBConnectTest();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("系统在连接易灵政务云盘服务器时产生如下错误：\r\n\r\n" + ex.ToString() + "\r\n\r\n 点击【确定】将退出系统。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                ExitApplication();
            }
            string code = "";
            string msg = "";
            Common.GlobalUtil.GetJsonMsgResult(jsonMsg, out code, out msg);
            if (code != "0")
            {
                //sysSettingBLL.CloseSqlConnection();
                XtraMessageBox.Show(msg, "登录错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else
            {
               

                SplashScreenManager.CloseForm(false);
                loginNetdisk();
            }


        }
        /// <summary>
        /// 初始化排序字段
        /// </summary>
        private void InitOrderField()
        {
            DicColumnOrder = new Dictionary<string, string>();
            for (int i = 0; i < lvFile.Columns.Count; i++)
            {
                DicColumnOrder.Add(lvFile.Columns[i].Name, "");
            }
        }

        /// <summary>
        /// 浮动窗口调用子窗口 重新打开
        /// </summary>
        public void RestoreWindow()
        {
            this.Show();
            this.ShowInTaskbar = true;
        }




        #region 工具栏相关


        /// <summary>
        /// [已过时]设置按钮的Enabled属性
        /// <creator>wangl</creator>
        /// <date>2011-12-23</date>
        /// </summary>
        /// <param name="buttonName">按钮的text值</param>
        /// <param name="enabled">是否可用</param>
        ///[Obsolete("已过时,请选用SetButtonEnabledByName方法")]
        private void SetButtonsEnabled(string buttonCaption, bool enabled)
        {
            for (int i = 0; i < barMainManager.Items.Count; i++)
            {
                if (barMainManager.Items[i].Caption == buttonCaption)
                {
                    barMainManager.Items[i].Enabled = enabled;
                    break;
                }

            }
        }

        /// <summary>
        /// 获取工具栏项
        /// </summary>
        /// <param name="buttonCaption"></param>
        /// <returns></returns>
        private BarItem GetBarItem(string buttonCaption)
        {
            BarItem bi = null;
            for (int i = 0; i < barMainManager.Items.Count; i++)
            {
                if (barMainManager.Items[i].Caption == buttonCaption)
                {
                    bi = barMainManager.Items[i];
                    break;
                }

            }
            return bi;
        }
        /// <summary>
        /// 根据名字获取工具栏项
        /// </summary>
        /// <param name="buttonName"></param>
        /// <returns></returns>
        private BarItem GetBarItemByName(string buttonName)
        {
            BarItem bi = null;
            for (int i = 0; i < barMainManager.Items.Count; i++)
            {
                if (barMainManager.Items[i].Name == buttonName)
                {
                    bi = barMainManager.Items[i];
                    break;
                }

            }
            return bi;
        }
        /// <summary>
        /// 设置按钮的Enabled属性 (根据名字)
        /// <creator>wangl</creator>
        /// <date>2012-04-16</date>
        /// </summary>
        /// <param name="buttonName"></param>
        /// <param name="enabled"></param>
        private void SetButtonEnabledByName(string buttonName, bool enabled)
        {
            for (int i = 0; i < barMainManager.Items.Count; i++)
            {
                if (barMainManager.Items[i].Name == buttonName)
                {
                    barMainManager.Items[i].Enabled = enabled;
                    break;
                }

            }
        }
        /// <summary>
        /// 设置按钮的文本
        /// <creator>wangl</creator>
        /// <date>2012-04-16</date>
        /// </summary>
        /// <param name="buttonName"></param>
        /// <param name="buttonCaption"></param>
        private void SetButtnCaption(string buttonName, string buttonCaption)
        {
            for (int i = 0; i < barMainManager.Items.Count; i++)
            {
                if (barMainManager.Items[i].Name == buttonName)
                {
                    barMainManager.Items[i].Caption = buttonCaption;
                    break;
                }

            }
        }
        /// <summary>
        /// 设置按钮imageList中的imageIndex
        /// <creator>wangl</creator>
        /// <date>2012-04-16</date> 
        /// </summary>
        /// <param name="imgName"></param>
        /// <returns></returns>
        private void SetButtonImageIndex(string buttonName, string imgName, ImageCollection imgCollect)
        {
            for (int i = 0; i < barMainManager.Items.Count; i++)
            {
                if (barMainManager.Items[i].Name == buttonName)
                {
                    Image img = imgCollect.Images[imgName];
                    for (int j = 0; j < imgCollect.Images.Count; j++)
                    {
                        if (imgCollect.Images[j] == img)
                        {
                            barMainManager.Items[i].ImageIndex = j;
                            break;
                        }

                    }
                    break;
                }

            }

        }

        /// <summary>
        /// 刷新
        /// </summary>
        private void RefreshNetDisk()
        {
            BindLeftTree();
            lvBindDataByID(prjOrderField);
            StatusBarShowChange();
        }


        /// <summary>
        /// 上传
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonUpload(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            UploadNetDisk();
        }
        #region 上传相关

        /// <summary>
        /// 拖拽上传
        /// </summary>
        /// <param name="paths"></param>
        public void UploadnetDiskByDrag(string[] paths)
        {
            //  timerUpload.Enabled = false;
            #region 不需要重置

            //uploadingSameFileList = new List<string>();


            //             uploadingSameFileCoverList  = new List<string>();

            //         uploadingSameDirList = new List<string>();


            //  Base.GlobalParams.GLOBAL_ISCANCEL = false;//不处于取消状态
            #endregion
            //  uploadingList = new List<Model.NetDisk>();//初始化正在上传列表


            NetDisk.UploadFileClient uploadFileClient = new NetDisk.UploadFileClient();
            if (uploadpaths.Select(h => h.Uploadfilepath).Intersect(paths).Count() > 0)
            {
                XtraMessageBox.Show("已有相同文件在上传队列中,请选择其他文件", "提示");
                return;

            }
            else
            {

                // NotCoverPath.Clear();
                int oldtotalUploadCount = totalUploadCount;
                foreach (string path in paths)
                {
                    GetUploadCount(path, CurrentFID, ref totalUploadCount);
                }
                if (oldtotalUploadCount == totalUploadCount)
                {

                    return;
                }
                gvUploadDataBind();
                //产生所有上传对象
                List<UploadFileClient> TouploadPath = paths.Where(h => (!NotCoverPath.Contains(h)) | uploadingSameFileCoverList.Contains(h)).Select(h => new UploadFileClient() { DestFid = CurrentFID, Uploadfilepath = h }).ToList();
                uploadpaths.AddRange(TouploadPath);
                InitProgressUploading(totalUploadCount);
                timerUpload.Enabled = true;
                if (thread == null)
                {
                    //创建上传线程
                    //  thread = new Thread(new ParameterizedThreadStart(UploadingDoWork));
                    //   thread.Start(uploadpaths);
                    thread = new BackgroundWorker();
                    thread.WorkerSupportsCancellation = true;
                    thread.WorkerReportsProgress = false;
                    thread.DoWork += new DoWorkEventHandler(thread_DoWork);
                    thread.RunWorkerCompleted += new RunWorkerCompletedEventHandler(thread_RunWorkerCompleted);
                    thread.RunWorkerAsync();
                    easSimpleButton1.Visible = true;
                    easSimpleButton2.Visible = true;
                    easSimpleButton3.Visible = true;
                    easSimpleButton1.Enabled = false;
                    easSimpleButton2.Enabled = true;
                    easSimpleButton3.Enabled = true;
                    mre = new ManualResetEvent(true);
                }
                //  GetRibbonBarItemByName("upload").Enabled = false;
            }

            xtraTabControl2.SelectedTabPage = xtraTabControl2.TabPages[0];
        }
        private void UploadNetDisk()
        {
            //while (netDiskList[0].Step <= 100)
            //{
            //    netDiskList[0].Step += 1;

            //    Application.DoEvents();
            //    //当前线程挂起指定的时间,这个是为了演示 

            //    System.Threading.Thread.Sleep(100);

            //    dgrdUploading.RefreshDataSource();
            //}



            // timerUpload.Enabled = false;
            #region 不需要重置

            //uploadingSameFileList = new List<string>();


            //             uploadingSameFileCoverList  = new List<string>();

            //         uploadingSameDirList = new List<string>();


            ///   Base.GlobalParams.GLOBAL_ISCANCEL = false;//不处于取消状态
            #endregion
            // uploadingList = new List<Model.NetDisk>();//初始化正在上传列表



            CustormOpenFileDialog form = new CustormOpenFileDialog();
            NetDisk.UploadFileClient uploadFileClient = new NetDisk.UploadFileClient();

            DialogResult result = form.ShowDialog();
            if (result == DialogResult.OK)
            {
                string[] paths = form.FileNames;

                // totalUploadCount = 0;//所有上传的文件、文件夹数量

                //初始化正在上传进度条
                if (uploadpaths.Select(h => h.Uploadfilepath).Intersect(paths).Count() > 0)
                {
                    XtraMessageBox.Show("已有相同文件在上传队列中,请选择其他文件", "提示");

                    return;
                }
                else
                {

                    // NotCoverPath.Clear();
                    int oldtotalUploadCount = totalUploadCount;
                    foreach (string path in paths)
                    {
                        GetUploadCount(path, CurrentFID, ref totalUploadCount);
                    }
                    if (oldtotalUploadCount == totalUploadCount)
                    {

                        return;
                    }
                    gvUploadDataBind();
                    //产生所有上传对象
                    List<UploadFileClient> TouploadPath = paths.Where(h => (!NotCoverPath.Contains(h)) | uploadingSameFileCoverList.Contains(h)).Select(h => new UploadFileClient() { DestFid = CurrentFID, Uploadfilepath = h }).ToList();
                    uploadpaths.AddRange(TouploadPath);
                    InitProgressUploading(totalUploadCount);
                    timerUpload.Enabled = true;
                    if (thread == null)
                    {
                        //创建上传线程
                        //  thread = new Thread(new ParameterizedThreadStart(UploadingDoWork));
                        //   thread.Start(uploadpaths);
                        thread = new BackgroundWorker();
                        thread.WorkerSupportsCancellation = true;
                        thread.WorkerReportsProgress = false;
                        thread.DoWork += new DoWorkEventHandler(thread_DoWork);
                        thread.RunWorkerCompleted += new RunWorkerCompletedEventHandler(thread_RunWorkerCompleted);
                        thread.RunWorkerAsync();
                        easSimpleButton1.Visible = true;
                        easSimpleButton2.Visible = true;
                        easSimpleButton3.Visible = true;
                        easSimpleButton1.Enabled = false;
                        easSimpleButton2.Enabled = true;
                        easSimpleButton3.Enabled = true;
                        mre = new ManualResetEvent(true);
                    }
                    //  GetRibbonBarItemByName("upload").Enabled = false;
                }

                xtraTabControl2.SelectedTabPage = xtraTabControl2.TabPages[0];
            }
        }
        /// <summary>
        /// 上传线程取消事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void thread_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //throw new NotImplementedException();
            if (e.Cancelled)
            {

                timerUpload.Enabled = false;
                uploadingSameFileList = new List<string>();
                uploadingSameFileCoverList = new List<string>();
                uploadingSameDirList = new List<string>();
                uploadStep = 0;
                totalUploadCount = 0;

                ResetProgressUploading();//重置正在上传进度条
                easSimpleButton1.Visible = false;
                easSimpleButton2.Visible = false;
                easSimpleButton3.Visible = false;

                GetRibbonBarItemByName("upload").Enabled = true;
                RefreshNetDisk();
                NotCoverPath.Clear();
                uploadingList.Clear();
                uploadpaths.Clear();
                thread = null;
                GlobalParams.GLOBAL_ISCANCEL = false;
                if (uploadError == "")
                {
                    XtraMessageBox.Show("取消上传成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                }
                else
                {
                    uploadError = uploadError.Trim(',');
                    XtraMessageBox.Show(uploadError, "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    uploadError = "";
                }
            }
        }
        /// <summary>
        /// 上传线程工作函数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void thread_DoWork(object sender, DoWorkEventArgs e)
        {
            ///throw new NotImplementedException();
            string NetdiskDir = Base.GlobalParams.NetDiskServiceSVC.GetNetDiskDir();

            while (uploadpaths.Count > 0)
            {


                //逐个上传解决只读问题
                upload(uploadpaths[0].Uploadfilepath, NetdiskDir, uploadpaths[0].DestFid, e);
                uploadpaths.Remove(uploadpaths[0]);
            }
        }


        /// <summary>
        /// 线程里运行的上传方法
        /// </summary>
        /// <param name="obj"></param>
        public void UploadingDoWork(object obj)
        {
            // List<string> paths = obj as List<string>;

            //获取服务器云盘文件夹
            //string NetdiskDir = Base.GlobalParams.NetDiskServiceSVC.GetNetDiskDir();

            //while (uploadpaths.Count > 0)
            //{



            //    upload(uploadpaths[0], NetdiskDir, CurrentFID);
            //    uploadpaths.Remove(uploadpaths[0]);
            //}

        }
        /// <summary>
        /// 正在上传委托
        /// </summary>
        /// <param name="paths"></param>
        private delegate void UploadingDoWorkWT(string[] paths);
        //使用Invoke方法来设置进度条   
        private void RunWithInvoke(object arg)
        {

            if (InvokeRequired)
            {
                this.Invoke(new UploadingDoWorkWT(UploadingDoWork), arg);
            }
        }


        /// <summary>
        /// 递归获取文件、文件夹数量
        /// </summary>
        /// <param name="path"></param>
        public void GetUploadCount(string path, decimal FParentID, ref int totalUploadCount)
        {
            NetDisk.UploadFileClient uploadFileClient = new NetDisk.UploadFileClient();
            gvUploadAddPath(path);
            if (System.IO.File.Exists(path))//如果是文件，则加入
            {
                //如果父文件夹为0，则不需判断是否已存在 
                if (FParentID != 0)
                {
                    string FileName = path.Substring(path.LastIndexOf("\\") + 1);
                    //判断父文件夹下是否存在当前文件、文件夹 1 存在 0不存在
                    string sameID = Base.GlobalParams.NetDiskServiceSVC.GetSameFID(FParentID.ToString(), FileName);
                    if (sameID != "0")
                    {
                        uploadingSameFileList.Add(FileName);
                        string clientMd5 = "";
                        //判断MD5值是否一致，一致:不覆盖；不一致：询问覆盖。
                        try
                        {
                            clientMd5 = uploadFileClient.GetMD5HashFromFilePath(path);
                        }
                        catch (System.Exception ex)
                        {
                            uploadingSameFileList.Remove(FileName);
                            gvUploadDelPath(path);
                            NotCoverPath.Add(path);
                            string uploadError2 = "下列文件上传失败已取消上传，原因：本地文件被占用,请关闭后再试";
                            uploadError2 += FileName;
                            XtraMessageBox.Show(uploadError2);
                            // totalUploadCount -= 1;
                            return;
                        }
                        string serverMd5 = "";
                        jsonMsg = Base.GlobalParams.NetDiskServiceSVC.GetNetDisk(sameID);
                        Common.GlobalUtil.GetJsonMsgResult(jsonMsg, out code, out msg);
                        if (code != "0")
                        {
                            XtraMessageBox.Show(msg, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        else
                        {
                            JObject msgObj = JObject.Parse(JObject.Parse(jsonMsg)["msg"].ToString());
                            string JsonNetDiskModel = msgObj["JsonNetDiskModel"].ToString();
                            Model.NetDisk tmpNetDiskModel = JsonConvert.DeserializeObject<Model.NetDisk>(JsonNetDiskModel);

                            serverMd5 = tmpNetDiskModel.FMD5 == null ? "" : tmpNetDiskModel.FMD5;
                        }
                        if (clientMd5 != serverMd5)
                        {
                            if (DialogResult.Yes == XtraMessageBox.Show("当前文件夹下存在相同文件名【" + FileName + "】，是否覆盖？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                            {
                                uploadingSameFileCoverList.Add(FileName);
                                uploadingSameFileCoverList.Add(path);
                            }
                            else
                            {
                                uploadingSameFileList.Remove(FileName);
                                gvUploadDelPath(path);
                                NotCoverPath.Add(path);
                                totalUploadCount -= 1;
                            }
                        }
                    }
                }
                totalUploadCount += 1;
            }
            else if (System.IO.Directory.Exists(path))//如果是文件夹
            {
                string sameID = "0";
                //如果父文件夹为0，则不需判断是否已存在
                if (FParentID != 0)
                {
                    string DirName = path.Substring(path.LastIndexOf("\\") + 1);
                    //判断父文件夹下是否存在当前文件、文件夹 1 存在 0不存在
                    sameID = Base.GlobalParams.NetDiskServiceSVC.GetSameFID(FParentID.ToString(), DirName);
                    if (sameID != "0")
                    {
                        uploadingSameDirList.Add(DirName);
                    }
                }

                totalUploadCount += 1;
                //获取文件夹内的所有文件夹
                string[] childDirectorys = Directory.GetDirectories(path);
                foreach (string childDirectory in childDirectorys)
                {
                    GetUploadCount(childDirectory, decimal.Parse(sameID), ref totalUploadCount);
                }
                //获取文件夹内的所有文件
                string[] childFiles = Directory.GetFiles(path);
                foreach (string childFile in childFiles)
                {
                    GetUploadCount(childFile, decimal.Parse(sameID), ref totalUploadCount);
                }
            }
        }



        /// <summary>
        /// 递归上传文件或文件夹
        /// </summary>
        /// <param name="path">文件或者文件夹路径</param>
        /// <param name="OldPath">客户端所属文件夹路径</param>
        /// <param name="NetdiskDir">服务端网盘路径</param>
        public void upload(string path, string NetdiskDir, decimal FParentID, DoWorkEventArgs e)
        {
            NetDisk.UploadFileClient uploadFileClient = new NetDisk.UploadFileClient();
            if (System.IO.File.Exists(path))//如果是文件，则上传
            {
                if (!NotCoverPath.Contains(path) | uploadingSameFileCoverList.Contains(path))
                {
                    if (uploadingSameFileCoverList.Contains(path))
                    {
                        uploadingSameFileCoverList.Remove(path);
                    }
                    ////父级文件夹路径
                    //string parentPath = Base.GlobalParams.NetDiskServiceSVC.GetPathByPid(FParentID.ToString()) + "\\";

                    //string NewPath = NetdiskDir;
                    //if (parentPath != "")
                    //{
                    //    NewPath += parentPath;
                    //}

                    string FileName = path.Substring(path.LastIndexOf("\\") + 1);
                    string DestID = FParentID.ToString();
                    string extension = null;
                    if (path.LastIndexOf(".") >= 0)
                    {
                        extension = path.Substring(path.LastIndexOf(".") + 1);
                    }


                    //获取数据
                    Model.NetDisk netDiskModel = new Model.NetDisk();

                    try
                    {
                        //为了检测文件是否打开。
                        FileStream readStream = new FileStream(path, FileMode.Open, FileAccess.Read);
                        readStream.Close();

                        netDiskModel.FParentID = FParentID;
                        netDiskModel.FName = FileName;
                        netDiskModel.FSuffixName = extension;
                        netDiskModel.FType = "F";
                        //netDiskModel.FSize = readStream.Length;
                        netDiskModel.FLogID = Base.GlobalParams.GLOBAL_LOGID;
                        //netDiskModel.FMD5 = uploadFileClient.GetMD5HashFromFile(readStream);

                    }
                    catch
                    {
                        if (uploadError == "")
                        {

                            uploadError += "本地文件【" + FileName + "】被占用，请关闭后再试";
                        }

                        uploadStep += 1;
                        e.Cancel = true;
                        return;
                    }

                    string jsonNetDiskModel = JsonConvert.SerializeObject(netDiskModel);
                    if (thread.CancellationPending)
                    {
                        e.Cancel = true;
                    }
                    else
                    {
                        //等待上传线程锁
                        
                        //先判断是否文件名过长
                        if (FileName.Length > 195)
                        {
                            if (uploadError == "")
                            {
                                uploadError += "下列文件文件名过长不能上传：";
                            }
                            uploadError += FileName + ",";

                            uploadStep += 1;
                            e.Cancel = true;
                            return;
                        }
                        if (uploadingSameFileList.Contains(FileName))
                        {
                            //文件相同、覆盖原来文件
                            if (uploadingSameFileCoverList.Contains(FileName))//如果覆盖
                            {
                                bool IsCover = true;
                                string jsAlert = "";
                                if (!uploadFileClient.uploadSingle(path, DestID, true, jsonNetDiskModel, out jsAlert))
                                {
                                    XtraMessageBox.Show(jsAlert, "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                                }
                            }
                        }
                        else
                        {
                            bool IsCover = false;
                            string jsAlert = "";
                            if (!uploadFileClient.uploadSingle(path, DestID, true, jsonNetDiskModel, out jsAlert))
                            {
                                XtraMessageBox.Show(jsAlert, "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                            }
                        }
                        gvUploadDelPath(path);
                        uploadStep += 1;
                    }
                }
                else
                {

                    NotCoverPath.Remove(path);
                }
            }
            else if (System.IO.Directory.Exists(path))//如果是文件夹，则创建
            {
                decimal outFID = 0;

                //父级文件夹路径
                string parentPath = Base.GlobalParams.NetDiskServiceSVC.GetPathByPid(FParentID.ToString()) + "\\";

                string NewPath = NetdiskDir;
                if (parentPath != "")
                {
                    NewPath += parentPath;
                }

                string DirName = path.Substring(path.LastIndexOf("\\") + 1);
                string DestPath = NewPath + DirName;


                //获取数据
                Model.NetDisk netDiskModel = new Model.NetDisk();
                netDiskModel.FParentID = FParentID;
                netDiskModel.FName = DirName;
                netDiskModel.FSuffixName = null;
                netDiskModel.FType = "D";
                netDiskModel.FSize = 0;
                netDiskModel.FLogID = Base.GlobalParams.GLOBAL_LOGID;
                netDiskModel.FMD5 = null;

                string jsonNetDiskModel = JsonConvert.SerializeObject(netDiskModel);

                if (uploadingSameDirList.Contains(DirName))
                {
                    //文件夹相同：不插入数据、不添加文件夹；获取相同文件夹的ID
                    outFID = decimal.Parse(GlobalParams.NetDiskServiceSVC.GetSameFID(FParentID.ToString(), DirName));
                }
                else
                {
                    string jsAlert = "";
                    if (!uploadFileClient.createDirToServer(DestPath, jsonNetDiskModel, out jsAlert, out outFID))
                    {
                        XtraMessageBox.Show(jsAlert, "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    }
                }

                //获取文件夹内的所有文件夹
                string[] childDirectorys = Directory.GetDirectories(path);
                foreach (string childDirectory in childDirectorys)
                {
                    upload(childDirectory, NetdiskDir, outFID, e);
                }
                //获取文件夹内的所有文件
                string[] childFiles = Directory.GetFiles(path);
                foreach (string childFile in childFiles)
                {
                    upload(childFile, NetdiskDir, outFID, e);
                }
                gvUploadDelPath(path);
                uploadStep += 1;
            }
        }

        /// <summary>
        /// 重置正在上传进度条
        /// </summary>
        private void ResetProgressUploading()
        {
            dockPnlLoad.Visibility = DevExpress.XtraBars.Docking.DockVisibility.Hidden;//隐藏进度条
            BarCheckItem barItem = GetRibbonBarItemByName("loadbar") as BarCheckItem;//进度条按钮
            barItem.Checked = false;
            //显示正在上传面板

            progressUploading.Position = 0;
            panelUploading.Visible = false;
            dgrdUploading.Visible = false;
        }

        /// <summary>
        /// 初始化正在上传进度条
        /// </summary>
        private void InitProgressUploading(int totalUploadCount)
        {
            dockPnlLoad.Visibility = DevExpress.XtraBars.Docking.DockVisibility.Visible;//显示进度条
            BarCheckItem barItem = GetRibbonBarItemByName("loadbar") as BarCheckItem;//激活进度条按钮
            barItem.Checked = true;

            panelUploading.Visible = true;
            dgrdUploading.Visible = true;
            // uploadStep = 0;
            //设置一个最小值 
            progressUploading.Properties.Minimum = 0;
            progressUploading.EditValue = uploadStep;
            //设置一个最大值 
            progressUploading.Properties.Maximum = totalUploadCount;
            //设置步长，即每次增加的数 
            progressUploading.Properties.Step = 1;
            //设置进度条的样式 
            progressUploading.Properties.ProgressViewStyle = DevExpress.XtraEditors.Controls.ProgressViewStyle.Solid;
            //progressUploading.Position = 0;

            //初始化上传进度
        }
        /// <summary>
        /// 绑定上传进度
        /// </summary>
        private void gvUploadDataBind()
        {
            dgrdUploading.DataSource = uploadingList;
        }

        /// <summary>
        /// 增加上传文件
        /// </summary>
        /// <param name="path"></param>
        private void gvUploadAddPath(string path)
        {
            Model.NetDisk uploadingModel = new Model.NetDisk();
            uploadingModel.relPath = path;
            uploadingModel.FName = path.Substring(path.LastIndexOf("\\") + 1);
            uploadingModel.Step = 0;
            uploadingList.Add(uploadingModel);

            dgrdUploading.RefreshDataSource();
        }
        /// <summary>
        /// 删除已上传文件
        /// </summary>
        /// <param name="path"></param>
        private void gvUploadDelPath(string path)
        {
            Model.NetDisk netDiskItem = null;
            List<Model.NetDisk> tmpNetDiskList = (from c in uploadingList
                                                  where c.relPath == path
                                                  select c).ToList();

            if (tmpNetDiskList.Count > 0)
            {
                netDiskItem = tmpNetDiskList[0];
            }
            if (netDiskItem != null)
            {
                uploadingList.Remove(netDiskItem);
            }
        }

        private void gvUploadInit()
        {
            //隐藏最上面的GroupPanel
            this.gvUpload.OptionsView.ShowGroupPanel = false;
            //设置成一次选择一行，并且不能被编辑
            this.gvUpload.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus;
            this.gvUpload.OptionsBehavior.Editable = false;
            this.gvUpload.OptionsSelection.EnableAppearanceFocusedCell = false;
            //设置显示横向滚动条
            this.gvUpload.OptionsView.ColumnAutoWidth = false;
            this.gvUpload.OptionsView.ShowFooter = true;

            for (int i = 1; i < gvUpload.Columns.Count; i++)
            {
                gvUpload.Columns[i].OptionsColumn.AllowEdit = false;
            }



        }

        /// <summary>
        /// 上传定时器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timerUpload_Tick(object sender, EventArgs e)
        {
            progressUploading.EditValue = uploadStep;
            dgrdUploading.DataSource = uploadingList;
            dgrdUploading.RefreshDataSource();

            if (int.Parse(progressUploading.EditValue.ToString()) == progressUploading.Properties.Maximum)
            {
                Base.GlobalParams.GLOBAL_ISCANCEL = false;
                timerUpload.Enabled = false;
                uploadingSameFileList = new List<string>();
                uploadingSameFileCoverList = new List<string>();
                uploadingSameDirList = new List<string>();
                uploadStep = 0;
                totalUploadCount = 0;
                uploadingList.Clear();
                uploadpaths.Clear();
                NotCoverPath.Clear();
                thread = null;
                ResetProgressUploading();//重置正在上传进度条
                easSimpleButton1.Visible = false;
                easSimpleButton2.Visible = false;
                easSimpleButton3.Visible = false;
                if (uploadError == "")
                {
                    XtraMessageBox.Show("上传成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                }
                else
                {
                    uploadError = uploadError.Trim(',');
                    XtraMessageBox.Show(uploadError, "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    uploadError = "";
                }
                GetRibbonBarItemByName("upload").Enabled = true;
                RefreshNetDisk();
            }
        }




        #endregion

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonDelete(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            DelNetDisk();
        }

        /// <summary>
        /// 删除
        /// </summary>
        private void DelNetDisk()
        {
            string ids = "";
            foreach (ListViewItem item in lvFile.SelectedItems)
            {
                ids += item.SubItems["FID"].Text.Replace(",", "") + ",";
            }
            //如果右边没有选中数据，则获取左边的选中数据
            if (ids == "")
            {
                TreeListNode focusedNode = tlstLeft.FocusedNode;
                if (focusedNode != null)
                {
                    if (focusedNode.Tag.ToString() != RootFID.ToString())
                    {
                        ids += focusedNode.Tag.ToString() + ",";
                    }
                    else
                    {
                        XtraMessageBox.Show("根目录不允许删除", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                        return;
                    }
                }
            }

            ids = ids.Trim(',');
            if (ids == "")
            {
                XtraMessageBox.Show("请选择需要删除的文件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            else
            {
                //判断是否上传目标目录包含当前选中节点不能删除
                if (uploadpaths.Count > 0)
                {
                    string[] idList = ids.Split(',');
                    if (uploadpaths.Any(h => idList.Contains(h.DestFid.ToString())))
                    {
                        XtraMessageBox.Show("上传目标目录包含当前选中文件夹不能删除", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;

                    }

                }
                //判断是否下载队列中包含当前选中节点不能删除
                if (downloadFileClient != null)
                {
                    string[] idList = ids.Split(',');

                    //先转换为decimal
                    List<decimal> decimalids = idList.Select(h => decimal.Parse(h)).ToList();

                    //判断是否包含
                    if (downloadFileClient.downloadNetDiskList.Any(h => decimalids.Contains(decimal.Parse(h.FID.ToString()))))
                    {
                        XtraMessageBox.Show("下载队列包含当前选中文件夹或文件不能删除", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;

                    }

                }

                if (DialogResult.OK == XtraMessageBox.Show("是否删除选中文件", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk))
                {
                    string jsonMsg = Base.GlobalParams.NetDiskServiceSVC.DelNetDisk(ids);
                    Common.GlobalUtil.GetJsonMsgResult(jsonMsg, out code, out msg);
                    if (code != "0")
                    {
                        XtraMessageBox.Show(msg, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        string[] idList = ids.Split(',');
                        if (idList.Contains(CurrentFID.ToString()))//如果删除了当前节点,上级节点获得焦点
                        {
                            if (tlstLeft.FocusedNode.ParentNode != null)
                            {
                                CurrentFID = decimal.Parse(tlstLeft.FocusedNode.ParentNode.Tag.ToString());
                            }
                            else
                            {
                                CurrentFID = 0;
                            }
                        }
                        RefreshNetDisk();
                        XtraMessageBox.Show("删除成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    }
                }
            }
        }

        /// <summary>
        /// 新建文件夹
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonCreateDir(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            createDirNetDisk();
        }

        private void createDirNetDisk()
        {
            Model.CommonDlgParameters commonDlgParameters = new Model.CommonDlgParameters();
            commonDlgParameters.ActionMethod = Model.ActionMethodType.Newdir;
            NetDisk.DirNameInputDlgForm dirNameInputDlgForm = new NetDisk.DirNameInputDlgForm(commonDlgParameters);
            if (dirNameInputDlgForm.ShowDialog() == DialogResult.OK)
            {

                string newDirName = dirNameInputDlgForm.NewName;
                //先做判断是否包含特殊字符
                if (StringContainsStrings(newDirName, new string[] { ",", "/", "|", ":", "*", "?", "<", ">" }))
                {
                    XtraMessageBox.Show("新建文件夹失败原因:不能包含特殊字符", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                Model.NetDisk netDiskModel = new Model.NetDisk();
                netDiskModel.FParentID = CurrentFID;
                netDiskModel.FName = newDirName;
                netDiskModel.FSuffixName = null;
                netDiskModel.FType = "D";
                netDiskModel.FSize = 0;
                netDiskModel.FLogID = Base.GlobalParams.GLOBAL_LOGID;
                netDiskModel.FMD5 = null;

                string JsonNetDiskModel = JsonConvert.SerializeObject(netDiskModel);

                string jsonMsg = Base.GlobalParams.NetDiskServiceSVC.CreateDirNetDisk(JsonNetDiskModel);
                Common.GlobalUtil.GetJsonMsgResult(jsonMsg, out code, out msg);
                if (code != "0")
                {
                    XtraMessageBox.Show(msg, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    XtraMessageBox.Show("新建文件夹成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    RefreshNetDisk();

                    JObject msgObj = JObject.Parse(JObject.Parse(jsonMsg)["msg"].ToString());
                    string fid = msgObj["FID"].ToString();
                    RefreshNodeByNodeFID(fid);
                }
            }




        }

        /// <summary>
        /// 下载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonDownLoad(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            DownloadNetDisk();
        }

        #region 下载相关

        private void DownloadNetDisk()
        {
            //  timerDownload.Enabled = false;

            List<string> idList = new List<string>();
            foreach (ListViewItem item in lvFile.SelectedItems)
            {
                idList.Add(item.SubItems["FID"].Text);
            }

            //如果右边没有选中数据，则获取左边的选中数据
            if (idList.Count == 0)
            {
                TreeListNode focusedNode = tlstLeft.FocusedNode;
                if (focusedNode != null)
                {
                    if (focusedNode.Tag.ToString() != RootFID.ToString())
                    {
                        idList.Add(focusedNode.Tag.ToString());
                    }
                    else
                    {
                        if (DialogResult.OK == XtraMessageBox.Show("是否下载根目录下的所有文件？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                        {
                            idList.Add(focusedNode.Tag.ToString());
                        }
                        else
                        {
                            return;
                        }
                    }
                }
            }





            if (idList.Count == 0)
            {
                XtraMessageBox.Show("请选择文件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }

            else
            {
                if (downloadFileClient == null)
                {



                    FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
                    if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
                    {
                        downloadFileClient = new NetDisk.DownloadFileClient();
                        downloadFileClient.idList = idList;
                        downloadFileClient.downloadDestPath = folderBrowserDialog.SelectedPath;


                        List<Model.NetDisk> downloadNetDiskList = new List<Model.NetDisk>();
                        GetDownloadCount(idList, ref downloadNetDiskList);
                        downloadFileClient.downloadNetDiskList = downloadNetDiskList;

                        //初始化正在下载进度条
                        InitProgressDownloading(downloadFileClient.downloadNetDiskList.Count);
                        gvDownloadDataBind();//绑定下载列表

                        timerDownload.Enabled = true;
                        if (thread1 == null)
                        {
                            //创建下载线程
                            thread1 = new BackgroundWorker();
                            thread1.WorkerSupportsCancellation = true;
                            thread1.WorkerReportsProgress = false;
                            thread1.DoWork += new DoWorkEventHandler(thread1_DoWork);
                            thread1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(thread1_RunWorkerCompleted);
                            thread1.RunWorkerAsync();
                            // thread1 = new Thread(new ParameterizedThreadStart(DownloadingDoWork));
                            // thread1.Start(downloadFileClient);
                            easSimpleButton4.Visible = true;
                            easSimpleButton5.Visible = true;
                            easSimpleButton6.Visible = true;
                            easSimpleButton4.Enabled = false;
                            easSimpleButton5.Enabled = true;
                            easSimpleButton6.Enabled = true;
                            mre2 = new ManualResetEvent(true);

                        }

                    }
                }
                else
                {

                    if (downloadFileClient.idList.Intersect(idList).Count() > 0)
                    {
                        XtraMessageBox.Show("已有相同文件在下载队列中,请选择其他文件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    }
                    else
                    {



                        List<Model.NetDisk> downloadNetDiskList = new List<Model.NetDisk>();
                        // GetDownloadCount(idList, ref downloadNetDiskList);
                        for (int i = 0; i < idList.Count; i++)
                        {
                            //获取下级文件/文件夹
                            string JsonNetDiskList = Base.GlobalParams.NetDiskServiceSVC.GetListCTE(idList[i], "", "");
                            List<Model.NetDisk> tmpNetDiskList = JsonConvert.DeserializeObject<List<Model.NetDisk>>(JsonNetDiskList);
                            downloadNetDiskList.AddRange(tmpNetDiskList);
                        }
                        if (downloadFileClient.downloadNetDiskList.Select(h => h.FID).ToList().Intersect(downloadNetDiskList.Select(h => h.FID).ToList()).Count() > 0)
                        {
                            XtraMessageBox.Show("已有相同文件在下载队列中,请选择其他文件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                            return;
                        }
                        else
                        {

                            gvDownloadAddPath(downloadNetDiskList);//添加正在下载列表
                            downloadFileClient.downloadNetDiskList.AddRange(downloadNetDiskList);
                            downloadFileClient.idList.AddRange(idList);

                            //初始化正在下载进度条
                            InitProgressDownloading(downloadFileClient.downloadNetDiskList.Count);
                            gvDownloadDataBind();//绑定下载列表

                            timerDownload.Enabled = true;
                            if (thread1 == null)
                            {

                                //创建下载线程
                                thread1 = new BackgroundWorker();
                                thread1.WorkerSupportsCancellation = true;
                                thread1.WorkerReportsProgress = false;
                                thread1.DoWork += new DoWorkEventHandler(thread1_DoWork);
                                thread1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(thread1_RunWorkerCompleted);
                                thread1.RunWorkerAsync();
                                // thread1 = new Thread(new ParameterizedThreadStart(DownloadingDoWork));
                                // thread1.Start(downloadFileClient);
                                easSimpleButton4.Visible = true;
                                easSimpleButton5.Visible = true;
                                easSimpleButton6.Visible = true;
                                easSimpleButton4.Enabled = false;
                                easSimpleButton5.Enabled = true;
                                easSimpleButton6.Enabled = true;
                                mre2 = new ManualResetEvent(true);

                            }
                        }
                    }
                }
            }
            xtraTabControl2.SelectedTabPage = xtraTabControl2.TabPages[1];
        }
        /// <summary>
        /// 下载线程取消事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void thread1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //throw new NotImplementedException();

            if (e.Cancelled)
            {
                timerDownload.Enabled = false;
                downloadingList.Clear();
                ResetProgressDownloading(); //重置正在下载进度条
                downloadStep = 0;
                downloadFileClient = null;

                // XtraMessageBox.Show("下载成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                GetRibbonBarItemByName("download").Enabled = true;
                thread1 = null;
                easSimpleButton4.Visible = false;
                easSimpleButton5.Visible = false;
                easSimpleButton6.Visible = false;

            }
        }
        /// <summary>
        /// 下载线程工作事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void thread1_DoWork(object sender, DoWorkEventArgs e)
        {
            //throw new NotImplementedException();

            string NetdiskDir = Base.GlobalParams.NetDiskServiceSVC.GetNetDiskDir();

            //foreach (string id in idList)
            //{
            //    //获取第一层文件
            //    List<Model.NetDisk> netDiskList = (from c in downloadNetDiskList
            //                                       where c.FID == decimal.Parse(id)
            //                                       select c).ToList();
            //    //递归下载文件
            //    download(downloadNetDiskList, id, downloadDestPath, NetdiskDir);
            //}

            //使用while解决只读问题
            while (downloadFileClient.idList.Count > 0)
            {
                string downloadDestPath = downloadFileClient.downloadDestPath;
                //需要下载的所有文件/文件夹
                List<Model.NetDisk> downloadNetDiskList = downloadFileClient.downloadNetDiskList;
                download(downloadNetDiskList, downloadFileClient.idList[0], downloadDestPath, NetdiskDir, e);
                downloadFileClient.idList.Remove(downloadFileClient.idList[0]);
                //  downloadFileClient.downloadNetDiskList.Remove(downloadFileClient.downloadNetDiskList[0]);
            }
        }






        /// <summary>
        /// 递归获取文件、文件夹数量
        /// </summary>
        /// <param name="path"></param>
        private void GetDownloadCount(List<string> idList, ref List<Model.NetDisk> downloadNetDiskList)
        {
            for (int i = 0; i < idList.Count; i++)
            {
                //获取下级文件/文件夹
                string JsonNetDiskList = Base.GlobalParams.NetDiskServiceSVC.GetListCTE(idList[i], "", "");
                List<Model.NetDisk> tmpNetDiskList = JsonConvert.DeserializeObject<List<Model.NetDisk>>(JsonNetDiskList);
                downloadNetDiskList.AddRange(tmpNetDiskList);
            }

            gvDownloadAddPath(downloadNetDiskList);//添加正在下载列表
        }





        /// <summary>
        /// 线程里运行的下载方法
        /// </summary>
        /// <param name="obj"></param>
        public void DownloadingDoWork(object obj)
        {
            //  NetDisk.DownloadFileClient downloadFileClient = obj as NetDisk.DownloadFileClient;

            //需要下载的第一层ID列表
            //  List<string> idList = downloadFileClient.idList;
            //下载目标路径

            //获取服务器云盘文件夹
            string NetdiskDir = Base.GlobalParams.NetDiskServiceSVC.GetNetDiskDir();

            //foreach (string id in idList)
            //{
            //    //获取第一层文件
            //    List<Model.NetDisk> netDiskList = (from c in downloadNetDiskList
            //                                       where c.FID == decimal.Parse(id)
            //                                       select c).ToList();
            //    //递归下载文件
            //    download(downloadNetDiskList, id, downloadDestPath, NetdiskDir);
            //}
            while (downloadFileClient.idList.Count > 0)
            {
                string downloadDestPath = downloadFileClient.downloadDestPath;
                //需要下载的所有文件/文件夹
                List<Model.NetDisk> downloadNetDiskList = downloadFileClient.downloadNetDiskList;
                //   注释一行
                // download(downloadNetDiskList, downloadFileClient.idList[0], downloadDestPath, NetdiskDir);
                downloadFileClient.idList.Remove(downloadFileClient.idList[0]);
                //  downloadFileClient.downloadNetDiskList.Remove(downloadFileClient.downloadNetDiskList[0]);
            }


        }
        /// <summary>
        /// 正在上传委托
        /// </summary>
        /// <param name="paths"></param>
        private delegate void DownloadingDoWorkWT(NetDisk.DownloadFileClient downloadFileClient);
        //使用Invoke方法来设置进度条   
        private void RunWithInvokeDownload(object arg)
        {
            if (InvokeRequired)
            {
                this.Invoke(new DownloadingDoWorkWT(DownloadingDoWork), arg);
            }
        }
        private void download(List<Model.NetDisk> downloadNetDiskList, string FParentID, string path, string NetdiskDir, DoWorkEventArgs e)
        {
            NetDisk.DownloadFileClient downloadFileClient = new NetDisk.DownloadFileClient();
            //获取当前文件
            List<Model.NetDisk> netDiskList = (from c in downloadNetDiskList
                                               where c.FID == decimal.Parse(FParentID)
                                               select c).ToList();
            if (netDiskList.Count > 0)
            {
                if (netDiskList[0].FType == "D")//如果是文件夹，创建文件夹
                {
                    string DestPath = path + "\\" + netDiskList[0].FName;
                    Common.serverIO.CreateDir(DestPath);

                    //获取子文件
                    List<Model.NetDisk> childNetDiskList = (from c in downloadNetDiskList
                                                            where c.FParentID != null && c.FParentID.Value == netDiskList[0].FID
                                                            select c).ToList();
                    foreach (Model.NetDisk childNetDiskModel in childNetDiskList)
                    {
                        download(downloadNetDiskList, childNetDiskModel.FID.ToString(), DestPath, NetdiskDir, e);
                    }
                    gvDownloadDelPath(netDiskList[0].FID.ToString());
                    downloadStep += 1;
                }
                else//如果是文件，直接下载
                {
                    string oldname = netDiskList[0].FName;
                    //先生成临时文件名
                    string repname = CheckDownloadFileName(path, netDiskList[0].FName);
                    string SrcPath = NetdiskDir + netDiskList[0].relPath;
                    string DestPath = path + "\\" + repname + ".elingsoft";
                    //最终要生成的文件名
                    string DestPathEnd = path + "\\" + repname;
                    if (thread1.CancellationPending)
                    {
                        e.Cancel = true;
                    }
                    else
                    {

                       
                        //下载压缩文件
                        downloadFileClient.DownloadSingle(SrcPath, DestPath);

                        System.IO.File.Move(DestPath, DestPathEnd);
                        gvDownloadDelPath(netDiskList[0].FID.ToString());
                        downloadStep += 1;
                    }
                }
            }

        }
        /// <summary>
        /// 生成要替换的文件名
        /// </summary>
        /// <param name="path"></param>
        /// <param name="fname"></param>
        /// <returns></returns>
        public string CheckDownloadFileName(string path, string fname)
        {

            string DestPath = path + "\\" + fname;
            string filenamewithoutext;
            string ext;

            string filenamewithoutextout = fname;
            if (fname.LastIndexOf('.') != -1)
            {
                filenamewithoutext = fname.Substring(0, fname.LastIndexOf('.'));
                ext = fname.Substring(fname.LastIndexOf('.') + 1);
            }
            else
            {
                filenamewithoutext = fname;
                ext = string.Empty;
            }
            int i = 0;
            while (System.IO.File.Exists(DestPath))
            {
                i++;
                if (string.IsNullOrEmpty(ext))
                {
                    DestPath = path + "\\" + filenamewithoutext + "(" + i + ")";
                    filenamewithoutextout = filenamewithoutext + "(" + i + ")";
                }
                else
                {
                    DestPath = path + "\\" + filenamewithoutext + "(" + i + ")" + "." + ext;
                    filenamewithoutextout = filenamewithoutext + "(" + i + ")" + "." + ext;
                }





            }

            return filenamewithoutextout;
        }
        /// <summary>
        /// 重置正在下载进度条
        /// </summary>
        private void ResetProgressDownloading()
        {
            dockPnlLoad.Visibility = DevExpress.XtraBars.Docking.DockVisibility.Hidden;//隐藏进度条
            BarCheckItem barItem = GetRibbonBarItemByName("loadbar") as BarCheckItem;//进度条按钮
            barItem.Checked = false;
            //显示正在上传面板

            progressDownloading.Position = 0;
            panelDownload.Visible = false;
            dgrdDownloading.Visible = false;
        }

        /// <summary>
        /// 初始化正在上传进度条
        /// </summary>
        private void InitProgressDownloading(int totalDownCount)
        {
            dockPnlLoad.Visibility = DevExpress.XtraBars.Docking.DockVisibility.Visible;//显示进度条
            BarCheckItem barItem = GetRibbonBarItemByName("loadbar") as BarCheckItem;//激活进度条按钮
            barItem.Checked = true;

            panelDownload.Visible = true;
            dgrdDownloading.Visible = true;
            //  downloadStep = 0;//初始化下载进度
            progressDownloading.EditValue = downloadStep;
            //设置一个最小值 
            progressDownloading.Properties.Minimum = 0;
            //设置一个最大值 
            progressDownloading.Properties.Maximum = totalDownCount;
            //设置步长，即每次增加的数 
            progressDownloading.Properties.Step = 1;
            //设置进度条的样式 
            progressDownloading.Properties.ProgressViewStyle = DevExpress.XtraEditors.Controls.ProgressViewStyle.Solid;
            progressDownloading.Position = 0;


        }

        /// <summary>
        /// 绑定下载进度
        /// </summary>
        private void gvDownloadDataBind()
        {
            dgrdDownloading.DataSource = downloadingList;
        }

        /// <summary>
        /// 增加下载文件
        /// </summary>
        /// <param name="path"></param>
        private void gvDownloadAddPath(List<Model.NetDisk> netDiskList)
        {
            downloadingList.AddRange(netDiskList);

            dgrdDownloading.RefreshDataSource();
        }
        /// <summary>
        /// 删除已下载文件
        /// </summary>
        /// <param name="path"></param>
        private void gvDownloadDelPath(string FID)
        {
            Model.NetDisk netDiskItem = null;
            List<Model.NetDisk> tmpNetDiskList = (from c in downloadingList
                                                  where c.FID == decimal.Parse(FID)
                                                  select c).ToList();

            if (tmpNetDiskList.Count > 0)
            {
                netDiskItem = tmpNetDiskList[0];
            }
            if (netDiskItem != null)
            {
                downloadingList.Remove(netDiskItem);
            }


        }


        /// <summary>
        /// 初始化正在下载
        /// </summary>
        private void gvDownloadInit()
        {
            //隐藏最上面的GroupPanel
            this.gvDownload.OptionsView.ShowGroupPanel = false;
            //设置成一次选择一行，并且不能被编辑
            this.gvDownload.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus;
            this.gvDownload.OptionsBehavior.Editable = false;
            this.gvDownload.OptionsSelection.EnableAppearanceFocusedCell = false;
            //设置显示横向滚动条
            this.gvDownload.OptionsView.ColumnAutoWidth = false;
            this.gvDownload.OptionsView.ShowFooter = true;

            for (int i = 1; i < gvDownload.Columns.Count; i++)
            {
                gvDownload.Columns[i].OptionsColumn.AllowEdit = false;
            }



        }

        private void timerDownload_Tick(object sender, EventArgs e)
        {
            progressDownloading.EditValue = downloadStep;
            dgrdDownloading.DataSource = downloadingList;
            dgrdDownloading.RefreshDataSource();


            if (int.Parse(progressDownloading.EditValue.ToString()) == progressDownloading.Properties.Maximum)
            {
                timerDownload.Enabled = false;
                downloadingList.Clear();
                ResetProgressDownloading(); //重置正在下载进度条
                downloadStep = 0;
                downloadFileClient = null;
                thread1 = null;
                XtraMessageBox.Show("下载成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                GetRibbonBarItemByName("download").Enabled = true;
                easSimpleButton4.Visible = false;
                easSimpleButton5.Visible = false;
                easSimpleButton6.Visible = false;
            }
        }


        #endregion

        /// <summary>
        /// 重命名
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonReName(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            RenameNetDisk();
        }

        private void RenameNetDisk()
        {
            List<string> idList = new List<string>();
            List<string> nameList = new List<string>();
            //右边数据
            foreach (ListViewItem item in lvFile.SelectedItems)
            {
                idList.Add(item.SubItems["FID"].Text.Replace(",", ""));
                if (item.SubItems["FType"].Text == "D")
                {
                    nameList.Add(item.SubItems["FName"].Text);
                }
                else
                {
                    string tmpName = item.SubItems["FName"].Text;
                    if (tmpName.LastIndexOf('.') >= 0)
                    {
                        tmpName = tmpName.Substring(0, tmpName.LastIndexOf('.'));
                    }
                    nameList.Add(tmpName);
                }
            }
            //如果右边没有选中数据，则获取左边的选中数据
            if (idList.Count == 0)
            {
                TreeListNode focusedNode = tlstLeft.FocusedNode;
                if (focusedNode != null)
                {
                    if (focusedNode.Tag.ToString() != RootFID.ToString())
                    {
                        idList.Add(focusedNode.Tag.ToString());
                        nameList.Add(focusedNode.GetDisplayText(0));
                    }
                    else
                    {
                        XtraMessageBox.Show("根目录不允许修改文件夹名字", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                        return;
                    }
                }
            }

            if (idList.Count == 0)
            {
                XtraMessageBox.Show("请选择需要重命名的文件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return;
            }
            else if (idList.Count > 1)
            {
                XtraMessageBox.Show("请只选择一个需要重命名的文件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return;
            }

            Model.CommonDlgParameters commonDlgParameters = new Model.CommonDlgParameters();
            commonDlgParameters.ActionMethod = Model.ActionMethodType.Rename;
            commonDlgParameters.StringList.Add(nameList[0]);
            NetDisk.DirNameInputDlgForm dirNameInputDlgForm = new NetDisk.DirNameInputDlgForm(commonDlgParameters);
            if (dirNameInputDlgForm.ShowDialog() == DialogResult.OK)
            {
                string newDirName = dirNameInputDlgForm.NewName;

                if (StringContainsStrings(newDirName, new string[] { ",", "/", "|", ":", "*", "?", "<", ">" }))
                {
                    XtraMessageBox.Show("重命名失败不能包含特殊字符", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                else
                {
                    string jsonMsg = Base.GlobalParams.NetDiskServiceSVC.RenameNetDisk(idList[0], newDirName);
                    Common.GlobalUtil.GetJsonMsgResult(jsonMsg, out code, out msg);
                    if (code != "0")
                    {
                        XtraMessageBox.Show(msg, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        RefreshNetDisk();
                        XtraMessageBox.Show("重命名成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    }
                }
            }
        }
        public bool StringContainsStrings(string src, string[] strs)
        {

            foreach (string s in strs)
            {

                if (src.Contains(s))
                {
                    return true;
                }
            }
            return false;
        }
        /// <summary>
        /// 移动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonMove(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            string ids = "";
            foreach (ListViewItem item in lvFile.SelectedItems)
            {
                ids += item.SubItems["FID"].Text.Replace(",", "") + ",";
            }
            //如果右边没有选中数据，则获取左边的选中数据
            if (ids == "")
            {
                TreeListNode focusedNode = tlstLeft.FocusedNode;
                if (focusedNode != null)
                {
                    if (focusedNode.Tag.ToString() != RootFID.ToString())
                    {
                        ids += focusedNode.Tag.ToString() + ",";
                    }
                    else
                    {
                        XtraMessageBox.Show("根目录不允许移动", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                        return;
                    }
                }
            }
            MoveNetDisk(ids);
        }

        private void MoveNetDisk(string ids)
        {
            if (ids == "")
            {
                XtraMessageBox.Show("请选择需要移动的文件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            else
            {
                NetDisk.DirSelectDlgForm dirSelectDlgForm = new NetDisk.DirSelectDlgForm();
                dirSelectDlgForm.DestDirID = CurrentFID;

                if (dirSelectDlgForm.ShowDialog() == DialogResult.OK)
                {
                    decimal DestDirID = dirSelectDlgForm.DestDirID;

                    jsonMsg = Base.GlobalParams.NetDiskServiceSVC.MoveNetDisk(ids, DestDirID.ToString());
                    Common.GlobalUtil.GetJsonMsgResult(jsonMsg, out code, out msg);

                    if (code != "0")
                    {
                        XtraMessageBox.Show(msg, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        RefreshNetDisk();
                    }
                    else
                    {
                        CurrentFID = DestDirID;
                        RefreshNetDisk();
                        XtraMessageBox.Show("移动成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    }

                }


            }
        }


        /// <summary>
        /// 复制
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonCopy(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            string ids = "";
            foreach (ListViewItem item in lvFile.SelectedItems)
            {
                ids += item.SubItems["FID"].Text.Replace(",", "") + ",";
            }
            //如果右边没有选中数据，则获取左边的选中数据
            if (ids == "")
            {
                TreeListNode focusedNode = tlstLeft.FocusedNode;
                if (focusedNode != null)
                {
                    if (focusedNode.Tag.ToString() != RootFID.ToString())
                    {
                        ids += focusedNode.Tag.ToString() + ",";
                    }
                    else
                    {
                        XtraMessageBox.Show("根目录不允许复制", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                        return;
                    }
                }
            }
            CopyNetDisk(ids);
        }

        private void CopyNetDisk(string ids)
        {
            if (ids == "")
            {
                XtraMessageBox.Show("请选择需要复制的文件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            else
            {
                NetDisk.DirSelectDlgForm dirSelectDlgForm = new NetDisk.DirSelectDlgForm();
                dirSelectDlgForm.DestDirID = CurrentFID;

                if (dirSelectDlgForm.ShowDialog() == DialogResult.OK)
                {
                    decimal DestDirID = dirSelectDlgForm.DestDirID;


                    jsonMsg = Base.GlobalParams.NetDiskServiceSVC.CopyNetDisk(ids, DestDirID.ToString());
                    Common.GlobalUtil.GetJsonMsgResult(jsonMsg, out code, out msg);

                    if (code != "0")
                    {
                        XtraMessageBox.Show(msg, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        RefreshNetDisk();
                    }
                    else
                    {
                        XtraMessageBox.Show("复制成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                        CurrentFID = DestDirID;
                        RefreshNetDisk();
                    }

                }
            }
        }


        /// <summary>
        /// 全选
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonSelectRowAll(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            lvFile.Focus();
            foreach (ListViewItem item in lvFile.Items)
            {
                item.Selected = true;
            }
        }



        /// <summary>
        /// 取消选中
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonUnselectRow(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            lvFile.Focus();
            foreach (ListViewItem item in lvFile.Items)
            {
                item.Selected = false;
            }
        }
        /// <summary>
        /// 全部反选
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonInverseSelectRowAll(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            lvFile.Focus();
            foreach (ListViewItem item in lvFile.Items)
            {
                item.Selected = !item.Selected;
            }
        }


        #endregion


        #region 地址栏



        /// <summary>
        /// 分类查看
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonLeftTree(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (dockPnlLeft.Visibility == DevExpress.XtraBars.Docking.DockVisibility.Visible)
            {
                dockPnlLeft.Hide();
            }
            else
            {
                dockPnlLeft.Show();
            }
        }

        /// <summary>
        /// 查看模式
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonShowMode(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ChangeShowMode();
            ChangeShowModeImg();
        }

        /// <summary>
        /// 改变显示状态
        /// </summary>
        private void ChangeShowMode()
        {
            if (showMode == "list")
            {
                lvFile.View = System.Windows.Forms.View.LargeIcon;
                showMode = "pic";
            }
            else if (showMode == "pic")
            {
                lvFile.View = System.Windows.Forms.View.Details;
                showMode = "list";
            }
        }
        /// <summary>
        /// 大小图标切换
        /// </summary>
        public void ChangeShowModeImg()
        {
            foreach (ListViewItem item in lvFile.Items)
            {
                if (item.Tag == null)
                {
                    item.ImageIndex = GetListViewImage(null, showMode, item.SubItems["FType"].Text);
                }
                else
                {
                    item.ImageIndex = GetListViewImage(item.Tag.ToString(), showMode, item.SubItems["FType"].Text);
                }
            }

        }


        /// <summary>
        /// 显示隐藏进度条
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonLoadBar(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ShowHideLoadBar();
        }

        private void ShowHideLoadBar()
        {
            if (dockPnlLoad.Visibility == DevExpress.XtraBars.Docking.DockVisibility.Visible)
            {
                dockPnlLoad.Hide();
                BarCheckItem barItem = GetRibbonBarItemByName("loadbar") as BarCheckItem;
                barItem.Checked = false;
            }
            else
            {
                dockPnlLoad.Show();
                BarCheckItem barItem = GetRibbonBarItemByName("loadbar") as BarCheckItem;
                barItem.Checked = true;
            }
        }

        /// <summary>
        /// 设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonUpset(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            OpenDialogWindow(typeof(NetDisk.SettingForm).ToString(), "设置", null);
        }

        /// <summary>
        /// 退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonLogout(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            notifyIcon1.Dispose();
            Application.Exit();
            this.Close();
        }

        /// <summary>
        /// 帮助主题
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonHelp(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //string chmPath = "";
            //Help.ShowHelp(new Control(), chmPath); 
        }

        /// <summary>
        /// 关于
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonAbout(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            OpenDialogWindow(typeof(HelpAbout.AboutDlgForm).ToString(), "关于", null);
        }
        /// <summary>
        /// 操作手册
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonManual(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            string chmPath = "网盘PC端操作手册.CHM";
            Help.ShowHelp(new Control(), chmPath);
        }

        #endregion









        #region 皮肤相关代码


        /// <summary>
        /// 递归绑定皮肤菜单事件
        /// <user>wangl</user>
        /// <date>2013-02-17</date> 
        /// </summary>
        private void BingSkinItemEvent(LinkPersistInfo liParent)
        {
            foreach (LinkPersistInfo liChild in ((BarSubItem)liParent.Item).LinksPersistInfo)
            {
                if (liChild.Item is BarSubItem)
                {
                    BingSkinItemEvent(liChild);
                }
                else
                {
                    liChild.Item.ItemClick += new ItemClickEventHandler(Item_MenuItemClick);
                    if (liParent.Item.Caption == DevExpress.LookAndFeel.UserLookAndFeel.Default.SkinName)
                    {
                        ((BarButtonItem)liParent.Item).ButtonStyle = BarButtonStyle.Check;
                    }
                }
            }
        }

        /// <summary>
        /// 点击皮肤样式菜单事件
        /// <user>wangl</user>
        /// <date>2012-03-03</date>
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Item_MenuItemClick(object sender, ItemClickEventArgs e)
        {
            //将皮肤名称写入到config文件中
            Common.ConfigHelper.SeTconfigKeyValue("SkinStyleName", e.Item.Caption);

        }
        #endregion


        #region 主窗体事件


        /// <summary>
        /// 关闭改为隐藏
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)//当用户点击窗体右上角X按钮或(Alt + F4)时 发生           
            {
                e.Cancel = true;
                this.ShowInTaskbar = false;
                this.Hide();
            }

        }

        private void MainForm_Resize(object sender, EventArgs e)
        {
            if (this.WindowState== FormWindowState.Minimized)
            {
                this.ShowInTaskbar = true;
            }

            ribbonNetdisk.Width = this.Width;
            RefreshAddrBar(CurrentFID.ToString());
        }

        /// <summary>
        /// 拖拽上传
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_DragDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.Text))
            {
                e.Effect = DragDropEffects.None;
                
                return;
            }
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                object objData = (System.Array)e.Data.GetData(DataFormats.FileDrop);
                string[] paths = objData as string[];
                UploadnetDiskByDrag(paths);
            }
        }

        private void MainForm_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.Text))
            {
                e.Effect = DragDropEffects.None;
                return;
            }
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Copy;
            }
        }

        #endregion








        private void dgrdUploading_EmbeddedNavigator_ButtonClick(object sender, NavigatorButtonClickEventArgs e)
        {

        }





        private void logoutzx(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.OK;

            this.Hide();
            try
            {
                Common.ConfigHelper.SeTconfigKeyValue("islogout", "Y");
                Application.Restart();
            }
            catch (Exception ee)
            {
                XtraMessageBox.Show(ee.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                ExitApplication();
            }
        }

        private void szToolStripMenuItem_Click(object sender, EventArgs e)
        {
            NetDisk.SettingForm stfm = new NetDisk.SettingForm();
            stfm.Owner = this;

            stfm.Show();
        }




        #region 列表管理
        private List<TreeListNode> ReturnFolder = new List<TreeListNode>();
        private int currentindex = 1;

        private BarEditItem mnuAddr;
        private BarEditItem mnuSearch;
        private BarButtonGroup bbgp;
        private int totalUploadCount = 0;
        private BackgroundWorker thread;
        private BackgroundWorker thread1;
        private NetDisk.DownloadFileClient downloadFileClient;


        /// 增加窗体的地址栏  
        /// <creator>wangl</creator>
        /// <date>2011-12-17</date>
        /// </summary>
        private void AddAddrBarItem()
        {
            //增加后台图标按钮
            //向后


            SuperToolTip sTooltip = new SuperToolTip();
            SuperToolTipSetupArgs sTooltipArgs = new SuperToolTipSetupArgs();

            BarButtonItem barButton = new BarButtonItem();
            barButton.Caption = "向后";
            barButton.Name = "mnuBackward";
            barButton.ButtonStyle = BarButtonStyle.Default;
            barButton.Border = BorderStyles.NoBorder;
            barButton.PaintStyle = BarItemPaintStyle.CaptionInMenu;
            barButton.ImageIndex = base.GetImageIndex("back_hover", imgCollectToolBar);
            barButton.ImageIndexDisabled = base.GetImageIndex("back_disabled", imgCollectToolBar);
            barButton.ItemClick += new ItemClickEventHandler(ButtonBackward);
            //添加提示
            sTooltip = new SuperToolTip();
            sTooltipArgs = new SuperToolTipSetupArgs();
            sTooltipArgs.Contents.Text = barButton.Caption;
            sTooltip.Setup(sTooltipArgs);
            barButton.SuperTip = sTooltip;

            barMdiAddr.AddItem(barButton);

            //向前
            barButton = new BarButtonItem();
            barButton.Caption = "向前";
            barButton.Name = "mnuForward";
            barButton.ButtonStyle = BarButtonStyle.Default;
            barButton.Border = BorderStyles.NoBorder;
            barButton.PaintStyle = BarItemPaintStyle.CaptionInMenu;
            barButton.ImageIndex = base.GetImageIndex("forward_hover", imgCollectToolBar);
            barButton.ImageIndexDisabled = base.GetImageIndex("forward_disabled", imgCollectToolBar);
            barButton.ItemClick += new ItemClickEventHandler(ButtonForward);
            //添加提示
            sTooltip = new SuperToolTip();
            sTooltipArgs = new SuperToolTipSetupArgs();
            sTooltipArgs.Contents.Text = barButton.Caption;
            sTooltip.Setup(sTooltipArgs);
            barButton.SuperTip = sTooltip;

            barMdiAddr.AddItem(barButton);

            //地址栏
            bbgp = new BarButtonGroup();
            bbgp.Name = "bgpn";


            barMdiAddr.AddItem(bbgp);



            mnuSearch = new BarEditItem();
            mnuSearch.Name = "mnuSearch";

            mnuSearch.EditValue = "";
            mnuSearch.AutoFillWidth = true;
            mnuSearch.AutoHideEdit = true;
            barMdiAddr.AddItem(mnuSearch);
            //搜索栏

            barButton = new BarButtonItem();
            barButton.Caption = "刷新";
            barButton.Name = "mnuSearch2";
            barButton.Width = 16;
            barButton.ButtonStyle = BarButtonStyle.Default;
            barButton.Border = BorderStyles.Default;
            barButton.ImageIndex = base.GetImageIndex("refresh_down", imgCollectToolBar);
            barButton.PaintStyle = BarItemPaintStyle.CaptionInMenu;
            barButton.ItemClick += new ItemClickEventHandler(barButton_ItemClick);
            //添加提示
            sTooltip = new SuperToolTip();
            sTooltipArgs = new SuperToolTipSetupArgs();
            sTooltipArgs.Contents.Text = barButton.Caption;
            sTooltip.Setup(sTooltipArgs);
            barButton.SuperTip = sTooltip;
            barMdiAddr.AddItem(barButton);
            DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit repositoryItemSearch = new DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit();
            repositoryItemSearch.Buttons[0].Kind = ButtonPredefines.Glyph;
            repositoryItemSearch.Buttons[0].Image = NetDiskPRJ.Properties.Resources.search_icon_hover;
            repositoryItemSearch.Buttons[0].Caption = "搜索";

            repositoryItemSearch.ButtonClick += new ButtonPressedEventHandler(barButton_ItemClicksearch);
            mnuSearch = new BarEditItem();
            mnuSearch.Name = "mnuSearch";
            mnuSearch.Width = 200;
            mnuSearch.Edit = repositoryItemSearch;
            mnuSearch.EditValue = "";
            //  mnuSearch.AutoFillWidth = true;
            barMdiAddr.AddItem(mnuSearch);



            //分类查看
            barButton = new BarButtonItem();
            barButton.Caption = "分类查看";
            barButton.Name = "mnuLeftTree";
            barButton.ButtonStyle = BarButtonStyle.Default;
            barButton.Border = BorderStyles.NoBorder;
            barButton.PaintStyle = BarItemPaintStyle.CaptionInMenu;
            barButton.ImageIndex = base.GetImageIndex("hide_leftsidebar_hover", imgCollectToolBar);
            barButton.ItemClick += new ItemClickEventHandler(ButtonLeftTree);
            //添加提示
            sTooltip = new SuperToolTip();
            sTooltipArgs = new SuperToolTipSetupArgs();
            sTooltipArgs.Contents.Text = barButton.Caption;
            sTooltip.Setup(sTooltipArgs);
            barButton.SuperTip = sTooltip;
            barMdiAddr.AddItem(barButton);

            //查看模式
            barButton = new BarButtonItem();
            barButton.Caption = "查看模式";
            barButton.Name = "mnuShowMode";
            barButton.ButtonStyle = BarButtonStyle.Default;
            barButton.Border = BorderStyles.NoBorder;
            barButton.PaintStyle = BarItemPaintStyle.CaptionInMenu;
            barButton.ImageIndex = base.GetImageIndex("Navigator_list_hover", imgCollectToolBar);
            barButton.ItemClick += new ItemClickEventHandler(ButtonShowMode);
            //添加提示
            sTooltip = new SuperToolTip();
            sTooltipArgs = new SuperToolTipSetupArgs();
            sTooltipArgs.Contents.Text = barButton.Caption;
            sTooltip.Setup(sTooltipArgs);
            barButton.SuperTip = sTooltip;
            barMdiAddr.AddItem(barButton);


        }




        /// <summary>
        /// 根据id更新地址栏
        /// </summary>
        /// <param name="FID"></param>
        private void RefreshAddrBar(string FID)
        {

            Dictionary<int, BarItem> bgp = new Dictionary<int, BarItem>();
            //  bbgp = (barMdiAddr.ItemLinks[2].Item as BarButtonGroup);
            bbgp.ClearLinks();
            GetFullDirPathByFid(FID, 0, bgp);
            bgp = bgp.Reverse().ToDictionary(p => p.Key, p => p.Value);
            BarCheckItem citm = new BarCheckItem();

            citm.Caption = "...";
            citm.RibbonStyle = DevExpress.XtraBars.Ribbon.RibbonItemStyles.SmallWithText;
            citm.PaintStyle = BarItemPaintStyle.CaptionGlyph;
            int imgidx = base.GetImageIndex("folder_nav_arrow_right", imgCollectToolBar);
            citm.ImageIndex = imgidx;
            Dictionary<int, BarItem> bgpnew = new Dictionary<int, BarItem>();
            //判断客户区大小
            if (this.WindowState == FormWindowState.Maximized)
            {
                if (Screen.PrimaryScreen.WorkingArea.Width > 1024)
                {
                    if (bgp.Count > 12)
                    {
                        KeyValuePair<int, BarItem> first = bgp.ToList().Take(1).FirstOrDefault();
                        Dictionary<int, BarItem> lasts = bgp.ToList().Skip(bgp.Count - 9).Take(9).ToDictionary(p => p.Key, p => p.Value);


                        // bgp.Values.ToList().Where(h=>h==null).FirstOrDefault() = citm;

                        bgpnew.Add(first.Key, first.Value);
                        bgpnew.Add(1, citm);
                        foreach (KeyValuePair<int, BarItem> kv in lasts)
                        {
                            bgpnew.Add(kv.Key, kv.Value);
                        }
                        bgp = bgpnew;
                    }

                }
                else
                {
                    if (bgp.Count > 10)
                    {
                        KeyValuePair<int, BarItem> first = bgp.ToList().Take(1).FirstOrDefault();
                        Dictionary<int, BarItem> lasts = bgp.ToList().Skip(bgp.Count - 7).Take(7).ToDictionary(p => p.Key, p => p.Value);


                        // bgp.Values.ToList().Where(h=>h==null).FirstOrDefault() = citm;

                        bgpnew.Add(first.Key, first.Value);
                        bgpnew.Add(1, citm);
                        foreach (KeyValuePair<int, BarItem> kv in lasts)
                        {
                            bgpnew.Add(kv.Key, kv.Value);
                        }
                        bgp = bgpnew;
                    }
                }
            }
            if (this.WindowState == FormWindowState.Normal)
            {
                int cnt = this.Width / 200;
                if (bgp.Count > cnt)
                {
                    KeyValuePair<int, BarItem> first = bgp.ToList().Take(1).FirstOrDefault();
                    Dictionary<int, BarItem> lasts = bgp.ToList().Skip(bgp.Count - cnt).Take(cnt).ToDictionary(p => p.Key, p => p.Value);


                    // bgp.Values.ToList().Where(h=>h==null).FirstOrDefault() = citm;

                    bgpnew.Add(first.Key, first.Value);
                    bgpnew.Add(1, citm);
                    foreach (KeyValuePair<int, BarItem> kv in lasts)
                    {
                        bgpnew.Add(kv.Key, kv.Value);
                    }
                    bgp = bgpnew;
                }

            }
            foreach (KeyValuePair<int, BarItem> kv in bgp)
            {
                kv.Value.Caption = AutoReSizeString(kv.Value.Caption);
                if (kv.Value != citm)
                {

                    (kv.Value as BarCheckItem).CheckedChanged += new ItemClickEventHandler(MainForm_CheckedChanged);
                }
                bbgp.AddItem(kv.Value);
            }
            //根据id绑定listview
            lvBindDataByID(prjOrderField);

            StatusBarShowChange();
            CheckArrowBar();
        }
        /// <summary>
        /// 自取使用字符串大小
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        private string AutoReSizeString(string p)
        {

            if (p.Length > 10)
            {
                return p.Substring(0, 9) + "..";
            }
            else
            {
                return p;
            }
        }
        /// <summary>
        /// 适应前进后退按钮
        /// </summary>
        private void CheckArrowBar()
        {

            if (currentindex > 1)
            {
                GetBarItemByName("mnuBackward").Enabled = true;
            }
            else
            {
                GetBarItemByName("mnuBackward").Enabled = false;
            }
            if (currentindex < ReturnFolder.Count)
            {
                GetBarItemByName("mnuForward").Enabled = true;
            }
            else
            {
                GetBarItemByName("mnuForward").Enabled = false;
            }

        }
        /// <summary>
        /// 获取所有树形控件节点
        /// </summary>
        /// <param name="tnlst"></param>
        /// <param name="tlstLeft"></param>
        private void getallnode(List<TreeListNode> tnlst, ElingAppSystemCtrls.EASTreeList tlstLeft)
        {
            for (int i = 0; i < tlstLeft.Nodes.Count; i++)
            {
                tnlst.Add(tlstLeft.Nodes[i]);
                getchldnd(tnlst, tlstLeft, tlstLeft.Nodes[i]);
            }
        }
        /// <summary>
        /// 递归子节点
        /// </summary>
        /// <param name="tnlst"></param>
        /// <param name="tlstLeft"></param>
        /// <param name="treeListNode"></param>
        private void getchldnd(List<TreeListNode> tnlst, ElingAppSystemCtrls.EASTreeList tlstLeft, TreeListNode treeListNode)
        {
            for (int i = 0; i < treeListNode.Nodes.Count; i++)
            {
                tnlst.Add(treeListNode.Nodes[i]);
                getchldnd(tnlst, tlstLeft, treeListNode.Nodes[i]);
            }
        }
        /// <summary>
        /// 地址栏按钮选中
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void MainForm_CheckedChanged(object sender, ItemClickEventArgs e)
        {
            BarCheckItem bct = (sender as BarCheckItem);
            string fid = Math.Round(decimal.Parse(bct.Tag.ToString()), 0).ToString();
            RefreshNodeByNodeFID(fid);
            //foreach (BarItemLink bi in bbgp.ItemLinks)
            //{
            //    if (!bi.Item.Equals(bct))
            //    {
            //        if ((bi.Item as BarCheckItem).Checked & bi is BarCheckItem)
            //        {

            //            (bi.Item as BarCheckItem).Checked = false;
            //        }
            //    }

            //}
        }
        /// <summary>
        /// 根据id刷新节点
        /// </summary>
        /// <param name="fid"></param>
        private void RefreshNodeByNodeFID(string fid)
        {
            List<TreeListNode> tnlst = new List<TreeListNode>();
            getallnode(tnlst, tlstLeft);

            TreeListNode n = tnlst.Where(h => Math.Round(decimal.Parse(h.Tag.ToString()), 0).ToString() == fid).ToList().FirstOrDefault();
            if (n != null)
            {

                tlstLeft.SetFocusedNode(n);


            }
        }
        /// <summary>
        /// 递归地址栏控件
        /// </summary>
        /// <param name="fid"></param>
        /// <param name="it"></param>
        /// <param name="bgp"></param>
        /// <returns></returns>
        private string GetFullDirPathByFid(string fid, int it, Dictionary<int, BarItem> bgp)
        {
            string fullpath = "";
            string strJson = Base.GlobalParams.NetDiskServiceSVC.GetDirByLogID(Base.GlobalParams.GLOBAL_LOGID);
            List<Model.NetDisk> dirList = JsonConvert.DeserializeObject<List<Model.NetDisk>>(strJson);
            if (dirList.Count > 0)
            {
                Model.NetDisk dirmd = (from m in dirList
                                       where m.FID.ToString() == fid
                                       select m).FirstOrDefault();
                // fullpath = dirmd.FName + fullpath;
                it--;
                BarCheckItem citm = new BarCheckItem();
                if (string.IsNullOrEmpty(dirmd.FParentID.ToString()))
                {
                    citm.Caption = "我的云盘";
                    citm.RibbonStyle = DevExpress.XtraBars.Ribbon.RibbonItemStyles.SmallWithText;
                    citm.PaintStyle = BarItemPaintStyle.CaptionGlyph;
                    int imgidx = base.GetImageIndex("home_highlight", imgCollectToolBar);
                    citm.ImageIndex = imgidx;

                }
                else
                {
                    citm.Caption = dirmd.FName.ToString();
                    citm.RibbonStyle = DevExpress.XtraBars.Ribbon.RibbonItemStyles.SmallWithText;
                    int imgidx = base.GetImageIndex("folder_nav_arrow_right", imgCollectToolBar);
                    citm.ImageIndex = imgidx;
                    citm.PaintStyle = BarItemPaintStyle.CaptionGlyph;
                }



                citm.Id = barMainManager.GetNewItemId();
                citm.Tag = dirmd.FID.ToString();

                bgp.Add(it, citm);
                GetParentPath(dirmd.FID.ToString(), it, ref bgp);
            }
            return fullpath;
        }
        /// <summary>
        /// 递归父级节点
        /// </summary>
        /// <param name="fid"></param>
        /// <param name="it"></param>
        /// <param name="bgp"></param>
        private void GetParentPath(string fid, int it, ref Dictionary<int, BarItem> bgp)
        {
            string strJson = Base.GlobalParams.NetDiskServiceSVC.GetDirByLogID(Base.GlobalParams.GLOBAL_LOGID);
            List<Model.NetDisk> dirList = JsonConvert.DeserializeObject<List<Model.NetDisk>>(strJson);
            if (dirList.Count > 0)
            {

                Model.NetDisk dirmd = (from m in dirList
                                       where m.FID.ToString() == fid
                                       select m).FirstOrDefault();

                string pid = dirmd.FParentID.ToString();
                Model.NetDisk pdirmd = (from m in dirList
                                        where m.FID.ToString() == pid
                                        select m).FirstOrDefault();
                if (pdirmd == null)
                {
                    return;
                }
                else
                {
                    it--;
                    BarCheckItem citm = new BarCheckItem();
                    ;
                    citm.Id = barMainManager.GetNewItemId();
                    citm.Tag = pid;
                    if (string.IsNullOrEmpty(pdirmd.FParentID.ToString()))
                    {
                        citm.Caption = "我的云盘";
                        citm.RibbonStyle = DevExpress.XtraBars.Ribbon.RibbonItemStyles.SmallWithText;
                        citm.PaintStyle = BarItemPaintStyle.CaptionGlyph;
                        int imgidx = base.GetImageIndex("home_highlight", imgCollectToolBar);
                        citm.ImageIndex = imgidx;
                    }
                    else
                    {

                        citm.Caption = pdirmd.FName.ToString();
                        citm.PaintStyle = BarItemPaintStyle.CaptionGlyph;
                        citm.RibbonStyle = DevExpress.XtraBars.Ribbon.RibbonItemStyles.SmallWithText;
                        int imgidx = base.GetImageIndex("folder_nav_arrow_right", imgCollectToolBar);
                        citm.ImageIndex = imgidx;
                    }
                    bgp.Add(it, citm);
                    // fullpath = pdirmd.FName + "\\" + fullpath;
                    GetParentPath(pdirmd.FID.ToString(), it, ref bgp);
                }
            }

        }
        //private void getallnode(List<TreeListNode> tnlst, ElingAppSystemCtrls.EASTreeList tlstLeft)
        //{
        //    for (int i = 0; i < tlstLeft.Nodes.Count; i++)
        //    {
        //        tnlst.Add(tlstLeft.Nodes[i]);
        //        getchldnd(tnlst, tlstLeft, tlstLeft.Nodes[i]);
        //    }
        //}

        //private void getchldnd(List<TreeListNode> tnlst, ElingAppSystemCtrls.EASTreeList tlstLeft, TreeListNode treeListNode)
        //{
        //    for (int i = 0; i < treeListNode.Nodes.Count; i++)
        //    {
        //        tnlst.Add(treeListNode.Nodes[i]);
        //        getchldnd(tnlst, tlstLeft, treeListNode.Nodes[i]);
        //    }
        //}
        /// <summary>
        /// 地址栏按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButton_ItemClick(object sender, EventArgs e)
        {
            //  RefreshNode();
            RefreshNetDisk();
            //  lvBindDataByID(prjOrderField);

            // StatusBarShowChange();
        }
        /// <summary>
        /// 刷新节点
        /// </summary>
        private void RefreshNode()
        {
            TreeListNode currentnode = ReturnFolder[currentindex - 1];
            if (currentnode != null)
            {

                string FID = currentnode.Tag.ToString();
                if (FID != CurrentFID.ToString())
                {



                    // this.mnuAddr.EditValue = GetFullDirPathByFid(FID);

                    lvBindDataByID(prjOrderField);
                }
            }
        }
        /// <summary>
        /// 搜索事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButton_ItemClicksearch(object sender, EventArgs e)
        {

            //   string editvalue = this.mnuSearch.EditValue.ToString();
            string editvalue = ((ButtonEdit)sender).Text;
            // this.mnuAddr.EditValue = "我的云盘："+editvalue + "的搜索结果";
            bbgp.ClearLinks();
            BarCheckItem citm = new BarCheckItem();

            citm.Caption = "我的云盘：";
            citm.RibbonStyle = DevExpress.XtraBars.Ribbon.RibbonItemStyles.SmallWithText;
            citm.PaintStyle = BarItemPaintStyle.CaptionGlyph;
            int imgidx = base.GetImageIndex("home_highlight", imgCollectToolBar);
            citm.ImageIndex = imgidx;
            citm.CheckedChanged += new ItemClickEventHandler(MainForm_CheckedChanged);
            citm.Id = barMainManager.GetNewItemId();
            //此处保存根节点
            citm.Tag = CurrentFID.ToString();

            bbgp.AddItem(citm);
            citm = new BarCheckItem();

            citm.Caption = editvalue + "的搜索结果";
            citm.RibbonStyle = DevExpress.XtraBars.Ribbon.RibbonItemStyles.SmallWithText;
            citm.PaintStyle = BarItemPaintStyle.CaptionGlyph;
            int imgidx2 = base.GetImageIndex("folder_nav_arrow_right", imgCollectToolBar);
            citm.ImageIndex = imgidx2;
            citm.Id = barMainManager.GetNewItemId();
            //此处保存根节点
            citm.Tag = CurrentFID.ToString();

            bbgp.AddItem(citm);


            //DataSet ds = new DataSet();

            //StringReader StrStream = null;
            //XmlTextReader Xmlrdr = null;

            ////读取字符串中的信息
            //StrStream = new StringReader(xmlData);
            ////获取StrStream中的数据
            //Xmlrdr = new XmlTextReader(StrStream);
            ////ds获取Xmlrdr中的数据                
            //ds.ReadXml(Xmlrdr);
            //var tb = ds.Tables[0].Select("FName like '%" + editvalue + "%'").CopyToDataTable();
            //  easGridControl1.DataSource = tb;
            if (!string.IsNullOrEmpty(editvalue))
            {

                //此处为根节点CurrentFID.
                prjWhere = "FName like '%" + editvalue + "%'";
                lvBindDataByWhere(prjWhere, prjOrderField);

            }
        }
        /// <summary>
        /// 向后
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonBackward(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (currentindex > 1)
            {
                TreeListNode tn = ReturnFolder[currentindex - 2];
                currentindex -= 2;
                tlstLeft.SetFocusedNode(tn);

                //  ReturnFolder.RemoveAt(ReturnFolder.Count - 1);



            }


            CheckArrowBar();


        }

        /// <summary>
        /// 向前
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonForward(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (currentindex < ReturnFolder.Count)
            {
                tlstLeft.SetFocusedNode(ReturnFolder[currentindex]);
                // ReturnFolder.RemoveAt(ReturnFolder.Count - 1);
            }
            CheckArrowBar();
        }
        /// <summary>
        /// 关于窗口事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            NetDiskPRJ.HelpAbout.AboutDlgForm abtfm = new NetDiskPRJ.HelpAbout.AboutDlgForm();
            abtfm.Owner = this;
            abtfm.Show();
        }
        /// <summary>
        /// 访问易灵软件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void visitelingsoft(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("http://www.elingsoft.com/");

        }

        /// <summary>
        /// listview双击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lvFile_DoubleClick(object sender, EventArgs e)
        {
            OpenNetDisk();

        }

        /// <summary>
        /// 配置按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnConfig_Click(object sender, EventArgs e)
        {
            this.cntMnuConfig.Show(Cursor.Position);
        }

        #endregion


        #region 文件操作右键菜单
        /// <summary>
        /// 打开
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cntOpen_Click(object sender, EventArgs e)
        {
            OpenNetDisk();
        }
        /// <summary>
        /// 打开列表项
        /// </summary>
        private void OpenNetDisk()
        {
            ////获取鼠标所在item
            //Point focusPoint = lvFile.PointToClient(Cursor.Position);
            //ListViewItem focusItem = lvFile.GetItemAt(focusPoint.X, focusPoint.Y);

            if (lvFile.SelectedItems.Count > 0)
            {
                ListViewItem focusItem = lvFile.SelectedItems[0];
                if (focusItem != null)
                {
                    if (focusItem.SubItems["FType"].Text == "D")
                    {
                        CurrentFID = decimal.Parse(focusItem.SubItems["FID"].Text);
                        //王成斌修改不能重置所有列表,应为会涉及到前进后退按钮功能
                        // RefreshNetDisk();
                        RefreshNodeByNodeFID(CurrentFID.ToString());
                    }
                }
            }
        }

        /// <summary>
        /// 下载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cntDownload_Click(object sender, EventArgs e)
        {
            DownloadNetDisk();
        }

        /// <summary>
        /// 复制
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cntCopy_Click(object sender, EventArgs e)
        {
            copyFIDs = "";
            foreach (ListViewItem item in lvFile.SelectedItems)
            {
                copyFIDs += item.SubItems["FID"].Text + ",";
            }
            copyFIDs = copyFIDs.Trim(',');
        }

        /// <summary>
        /// 剪切
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cntCut_Click(object sender, EventArgs e)
        {
            cutFIDs = "";
            foreach (ListViewItem item in lvFile.SelectedItems)
            {
                cutFIDs += item.SubItems["FID"].Text + ",";
            }
            cutFIDs = cutFIDs.Trim(',');
        }

        private void cntRename_Click(object sender, EventArgs e)
        {
            RenameNetDisk();
        }
        /// <summary>
        /// 粘贴
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cntPaste_Click(object sender, EventArgs e)
        {
            if (copyFIDs != "")//复制粘贴
            {
                //  CopyNetDisk(copyFIDs);

                jsonMsg = Base.GlobalParams.NetDiskServiceSVC.CopyNetDisk(copyFIDs, CurrentFID.ToString());
                Common.GlobalUtil.GetJsonMsgResult(jsonMsg, out code, out msg);

                //清空复制、剪切ID
                copyFIDs = "";
                cutFIDs = "";

                if (code != "0")
                {
                    XtraMessageBox.Show(msg, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                else
                {
                    XtraMessageBox.Show("复制成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);

                    RefreshNetDisk();
                }
            }
            else if (cutFIDs != "")//剪切粘贴
            {
                //  MoveNetDisk(cutFIDs);
                jsonMsg = Base.GlobalParams.NetDiskServiceSVC.MoveNetDisk(cutFIDs, CurrentFID.ToString());
                Common.GlobalUtil.GetJsonMsgResult(jsonMsg, out code, out msg);

                //清空复制、剪切ID
                copyFIDs = "";
                cutFIDs = "";

                if (code != "0")
                {
                    XtraMessageBox.Show(msg, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                else
                {
                    XtraMessageBox.Show("移动成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);

                    RefreshNetDisk();
                }


            }
        }
        /// <summary>
        /// 上传
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cntUpload_Click(object sender, EventArgs e)
        {
            UploadNetDisk();
        }
        /// <summary>
        /// 新建文件夹
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cntNewDir_Click(object sender, EventArgs e)
        {
            createDirNetDisk();
        }
        /// <summary>
        /// 移动到
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cntMove_Click(object sender, EventArgs e)
        {
            string ids = "";
            foreach (ListViewItem item in lvFile.SelectedItems)
            {
                ids += item.SubItems["FID"].Text.Replace(",", "") + ",";
            }
            MoveNetDisk(ids);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cntDelete_Click(object sender, EventArgs e)
        {
            DelNetDisk();
        }

        /// <summary>
        /// 右键显示按钮判断
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lvFile_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                //粘贴是否显示
                if (copyFIDs != "" || cutFIDs != "")
                {
                    cntPaste.Visible = true;
                }
                else
                {
                    cntPaste.Visible = false;
                }

                //其他按钮是否显示
                if (lvFile.SelectedItems.Count > 0)//如果有选中选项
                {
                    //如果选中项有文件夹
                    bool hasDir = false;
                    foreach (ListViewItem item in lvFile.SelectedItems)
                    {
                        if (item.SubItems["FType"].Text == "D")
                        {
                            hasDir = true;
                        }
                    }
                    if (hasDir)//如果有文件夹
                    {
                        cntOpen.Visible = true;
                        cntUpload.Visible = false;
                        cntDownload.Visible = true;
                        cntNewDir.Visible = false;
                        cntMove.Visible = true;
                        cntCopy.Visible = true;
                        cntCut.Visible = true;
                        cntRename.Visible = true;
                        cntDelete.Visible = true;
                    }
                    else//如果没有文件夹
                    {
                        cntOpen.Visible = false;
                        cntUpload.Visible = false;
                        cntDownload.Visible = true;
                        cntNewDir.Visible = false;
                        cntMove.Visible = true;
                        cntCopy.Visible = true;
                        cntCut.Visible = true;
                        cntRename.Visible = true;
                        cntDelete.Visible = true;
                    }
                }
                else//如果没有选中选项
                {
                    cntOpen.Visible = false;
                    cntUpload.Visible = true;
                    cntDownload.Visible = false;
                    cntNewDir.Visible = true;
                    cntMove.Visible = false;
                    cntCopy.Visible = false;
                    cntCut.Visible = false;
                    cntRename.Visible = false;
                    cntDelete.Visible = false;
                }
            }
        }

        #endregion

        #region 托盘相关
        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                myMenu.Show();
            }

            if (e.Button == MouseButtons.Left)
            {
                this.Show();
                this.Visible = true;
                this.WindowState = FormWindowState.Normal;
            }
        }
        /// <summary>
        /// 打开主程序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            RestoreWindow();
        }
        /// <summary>
        /// 设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cntUpset_Click(object sender, EventArgs e)
        {
            OpenDialogWindow(typeof(NetDisk.SettingForm).ToString(), "设置", null);
        }
        /// <summary>
        /// 退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cntLogout_Click(object sender, EventArgs e)
        {
            ExitApplication();
        }
        /// <summary>
        /// 退出
        /// </summary>
        private void ExitApplication()
        {
            notifyIcon1.Dispose();
            Application.Exit();
            this.Close();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cntOpenFloatForm_Click(object sender, EventArgs e)
        {
            myTopMost.SetFormShowHide(!myTopMost.IsShow);
            InitCntOpenFloatForm();
        }
        /// <summary>
        /// 修改显示/隐藏悬浮窗文字
        /// </summary>
        public void InitCntOpenFloatForm()
        {
            if (myTopMost.IsShow)
            {
                //如果已显示，则为隐藏悬浮窗
                cntOpenFloatForm.Text = "隐藏悬浮窗";
            }
            else
            {
                //如果已显示，则为显示悬浮窗
                cntOpenFloatForm.Text = "显示悬浮窗";
            }
        }
        #endregion
        /// <summary>
        /// /listview进入拖拽事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lvFile_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.Text))
            {
                e.Effect = DragDropEffects.None;
                return;
            }
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Copy;
            }
        }
        /// <summary>
        /// listview拖拽完成事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lvFile_DragDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.Text))
            {
                e.Effect = DragDropEffects.None;
               
                return;
            }
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                object objData = (System.Array)e.Data.GetData(DataFormats.FileDrop);
                string[] paths = objData as string[];
                UploadnetDiskByDrag(paths);
            }
        }
        #region 开始继续暂停按钮
        /// <summary>
        /// 上传继续按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void easSimpleButton1_Click(object sender, EventArgs e)
        {
            //释放上传线程锁
            mre.Set();
            easSimpleButton1.Enabled = false;
            easSimpleButton2.Enabled = true;
        }
        /// <summary>
        /// 上传暂停按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void easSimpleButton2_Click(object sender, EventArgs e)
        {
            //柱塞上传线程锁
            mre.Reset();
            easSimpleButton2.Enabled = false;
            easSimpleButton1.Enabled = true;
        }
        /// <summary>
        /// 上传取消按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void easSimpleButton3_Click(object sender, EventArgs e)
        {
            GlobalParams.GLOBAL_ISCANCEL = true;
            mre.Set();
            thread.CancelAsync();
            easSimpleButton1.Enabled = false;
            easSimpleButton2.Enabled = false;
            easSimpleButton3.Enabled = false;

        }
        /// <summary>
        /// 下载继续按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void easSimpleButton4_Click(object sender, EventArgs e)
        {
            //释放下载线程锁
            mre2.Set();
            easSimpleButton4.Enabled = false;
            easSimpleButton5.Enabled = true;
        }
        /// <summary>
        /// 下载暂停按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void easSimpleButton5_Click(object sender, EventArgs e)
        {
            //柱塞下载线程锁
            mre2.Reset();
            easSimpleButton5.Enabled = false;
            easSimpleButton4.Enabled = true;
        }
        /// <summary>
        /// 下载取消按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void easSimpleButton6_Click(object sender, EventArgs e)
        {

            mre2.Set();
            thread1.CancelAsync();
            easSimpleButton4.Enabled = false;
            easSimpleButton5.Enabled = false;
            easSimpleButton6.Enabled = false;
        }




        #endregion


        #region 拖拽功能函数

        /// <summary>
        /// listview被拖出的事件(旧方法)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lvFile_ItemDrag2(object sender, ItemDragEventArgs e)
        {
            //转化成数据源可以使用的对象
            List<ListViewItem> its = lvFile.SelectedItems.Cast<ListViewItem>().ToList();



            //先获得fid
            string[] paths = its.Select(h => h.SubItems["FID"].Text.Replace(",", "").ToString()).ToArray();
            //if (paths.Length>1)
            //{
            //    XtraMessageBox.Show("拖拽时只能选择1个对象");
            //    return;
            //}

            ShellDataObject data = new ShellDataObject();
            NetDiskPRJ.MainForm.CheckForIllegalCrossThreadCalls = false;
            data.onDownloadFid += DownloadFidmain;
            //将fid分2种类型存放
            // DataObject data = new DataObject(DataFormats.FileDrop, paths);
            data.SetData(DataFormats.FileDrop, paths);
            data.SetData(DataFormats.Text, paths);
            //执行拖拽
            lvFile.DoDragDrop(data, DragDropEffects.Move);
        }

        /// <summary>
        /// listview被拖出的事件新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lvFile_ItemDrag(object sender, ItemDragEventArgs e)
        {

            List<ListViewItem> its = lvFile.SelectedItems.Cast<ListViewItem>().ToList();

            //生成临时文件
            string filename = GlobalUtil.GenerateStringId() + ".tmp";
            string currentdir = System.IO.Path.GetTempPath();
           // string paths = currentdir + "\\NetDiskDownLoad.tmp";
            string pathstemp = currentdir +"\\"+ filename;
            FileStream fs = new FileStream(pathstemp, FileMode.Create);
            fs.Close();

             downloaddestpath = "";
           
            int i = 0;
            tempWatchers = new Hashtable();
            FileSystemWatcher watcher;
            //Adding FileSystemWatchers and adding Created event to it 

            if (tempWatchers.Count == 0)
            {

                foreach (string driveName in Directory.GetLogicalDrives())
                {
                    //this checking may sound absurd to you.
                    //but in OS like Windows 2000,
                    //even if there is no floppy drive present
                    //An "A:/" will be shown in My Computer.
                    //To avoid exceptions like this I've added this check.
                    if (Directory.Exists(driveName))
                    {
                        watcher = new FileSystemWatcher();
                       // watcher.Filter = "NetDiskDownLoad.tmp";
                        watcher.Filter = filename;
                        watcher.NotifyFilter = NotifyFilters.FileName;
                        watcher.Created += new FileSystemEventHandler(FileWatcherCreated);
                        watcher.IncludeSubdirectories = true;
                        watcher.Path = driveName;
                        watcher.EnableRaisingEvents = true;
                        tempWatchers.Add("file_watcher" + i.ToString(), watcher);
                        i = i + 1;
                    }
                }

            }
            //先获得fid
            string[] paths = its.Select(h => h.SubItems["FID"].Text.Replace(",", "").ToString()).ToArray();
            ShellDataObject data = new ShellDataObject();
            NetDiskPRJ.MainForm.CheckForIllegalCrossThreadCalls = false;
            data.onDownloadFid += DownloadFidmain;
            string[] paths3 = new string[1];

           // string currentdir = System.IO.Path.GetTempPath();
           // string paths = currentdir + "\\NetDiskDownLoad.tmp";
           // string currentdir = Directory.GetCurrentDirectory();
               //旧的临时文件路径
            //  paths3[0] = currentdir + "\\NetDiskDownLoad.tmp";
            paths3[0] = pathstemp;
            //将fid分2种类型存放
            // DataObject data = new DataObject(DataFormats.FileDrop, paths);
            data.SetData(DataFormats.FileDrop, paths3);
            data.SetData(DataFormats.Text, paths);
            //执行拖拽
            DragDropEffects dft = lvFile.DoDragDrop(data, DragDropEffects.Move);
           
            
           Thread.Sleep(1000);
          if(!string.IsNullOrEmpty(downloaddestpath))
            {
               
                string todownload = downloaddestpath;
                //string dropedFilePath = downloaddestpath + "\\NetDiskDownLoad.tmp";

                string dropedFilePath = downloaddestpath +"\\"+ filename;
                if (File.Exists(dropedFilePath))
                    File.Delete(dropedFilePath);
               
                
                DownloadNetDiskByDestPath(new List<string>(paths), todownload);



           }
          foreach (FileSystemWatcher fw in tempWatchers.Values)
          {
              fw.Created -= new FileSystemEventHandler(FileWatcherCreated);
              fw.Dispose();
          }
          tempWatchers.Clear();
          downloaddestpath = "";
        }

        private void lvFile_QueryContinueDrag(object sender, QueryContinueDragEventArgs e)
        {
            
              
           
        }
        /// <summary>
        /// 文件监视函数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void FileWatcherCreated(object sender, FileSystemEventArgs e)
        {
            try
            {
                OnFileDropPathFound(e.FullPath);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "DragNDrop Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// Methodd Called when the Dropped Path is found
        /// </summary>
        /// <param name="dropedFilePath"></param>
        private static void OnFileDropPathFound(string dropedFilePath)
        {
            try
            {
                //if (File.Exists(dropedFilePath))
                //    File.Delete(dropedFilePath);
                downloaddestpath = dropedFilePath.Substring(0, dropedFilePath.LastIndexOf('\\'));
                //  XtraMessageBox.Show(dropedFilePath);
            }
            catch (Exception ex)
            {

                XtraMessageBox.Show(ex.Message, "DragNDrop Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// 手动调用下载方法
        /// </summary>
        /// <param name="idList"></param>
        /// <param name="destpath"></param>
        private void DownloadNetDiskByDestPath(List<string> idList, string destpath)
        {
            //  timerDownload.Enabled = false;






            if (idList.Count == 0)
            {
                XtraMessageBox.Show("请选择文件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }

            else
            {
                if (downloadFileClient == null)
                {




                    downloadFileClient = new NetDisk.DownloadFileClient();
                    downloadFileClient.idList = idList;
                    downloadFileClient.downloadDestPath = destpath;


                    List<Model.NetDisk> downloadNetDiskList = new List<Model.NetDisk>();
                    GetDownloadCount(idList, ref downloadNetDiskList);
                    downloadFileClient.downloadNetDiskList = downloadNetDiskList;

                    //初始化正在下载进度条
                    InitProgressDownloading(downloadFileClient.downloadNetDiskList.Count);
                    gvDownloadDataBind();//绑定下载列表

                    timerDownload.Enabled = true;
                    if (thread1 == null)
                    {
                        //创建下载线程
                        thread1 = new BackgroundWorker();
                        thread1.WorkerSupportsCancellation = true;
                        thread1.WorkerReportsProgress = false;
                        thread1.DoWork += new DoWorkEventHandler(thread1_DoWork);
                        thread1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(thread1_RunWorkerCompleted);
                        thread1.RunWorkerAsync();
                        // thread1 = new Thread(new ParameterizedThreadStart(DownloadingDoWork));
                        // thread1.Start(downloadFileClient);
                        easSimpleButton4.Visible = true;
                        easSimpleButton5.Visible = true;
                        easSimpleButton6.Visible = true;
                        easSimpleButton4.Enabled = false;
                        easSimpleButton5.Enabled = true;
                        easSimpleButton6.Enabled = true;
                        mre2 = new ManualResetEvent(true);

                    }


                }
                else
                {

                    if (downloadFileClient.idList.Intersect(idList).Count() > 0)
                    {
                        XtraMessageBox.Show("已有相同文件在下载队列中,请选择其他文件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    }
                    else
                    {



                        List<Model.NetDisk> downloadNetDiskList = new List<Model.NetDisk>();
                        // GetDownloadCount(idList, ref downloadNetDiskList);
                        for (int i = 0; i < idList.Count; i++)
                        {
                            //获取下级文件/文件夹
                            string JsonNetDiskList = Base.GlobalParams.NetDiskServiceSVC.GetListCTE(idList[i], "", "");
                            List<Model.NetDisk> tmpNetDiskList = JsonConvert.DeserializeObject<List<Model.NetDisk>>(JsonNetDiskList);
                            downloadNetDiskList.AddRange(tmpNetDiskList);
                        }
                        if (downloadFileClient.downloadNetDiskList.Select(h => h.FID).ToList().Intersect(downloadNetDiskList.Select(h => h.FID).ToList()).Count() > 0)
                        {
                            XtraMessageBox.Show("已有相同文件在下载队列中,请选择其他文件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                            return;
                        }
                        else
                        {

                            gvDownloadAddPath(downloadNetDiskList);//添加正在下载列表
                            downloadFileClient.downloadNetDiskList.AddRange(downloadNetDiskList);
                            downloadFileClient.idList.AddRange(idList);

                            //初始化正在下载进度条
                            InitProgressDownloading(downloadFileClient.downloadNetDiskList.Count);
                            gvDownloadDataBind();//绑定下载列表

                            timerDownload.Enabled = true;
                            if (thread1 == null)
                            {

                                //创建下载线程
                                thread1 = new BackgroundWorker();
                                thread1.WorkerSupportsCancellation = true;
                                thread1.WorkerReportsProgress = false;
                                thread1.DoWork += new DoWorkEventHandler(thread1_DoWork);
                                thread1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(thread1_RunWorkerCompleted);
                                thread1.RunWorkerAsync();
                                // thread1 = new Thread(new ParameterizedThreadStart(DownloadingDoWork));
                                // thread1.Start(downloadFileClient);
                                easSimpleButton4.Visible = true;
                                easSimpleButton5.Visible = true;
                                easSimpleButton6.Visible = true;
                                easSimpleButton4.Enabled = false;
                                easSimpleButton5.Enabled = true;
                                easSimpleButton6.Enabled = true;
                                mre2 = new ManualResetEvent(true);

                            }
                        }
                    }
                }
            }
            xtraTabControl2.SelectedTabPage = xtraTabControl2.TabPages[1];
        }

        /// <summary>
        /// 数据源委托下载函数
        /// </summary>
        /// <param name="fids"></param>
        /// <returns></returns>
        public List<string> DownloadFidmain(string[] fidsall)
        {

            //先下载到临时目录
            NetDisk.DownloadFileClient downloadFileClient = new NetDisk.DownloadFileClient();
            string NetdiskDir = Base.GlobalParams.NetDiskServiceSVC.GetNetDiskDir();
            string path = System.IO.Path.GetTempPath();
            List<string> returnstrs = new List<string>();

            foreach (string fids in fidsall)
            {
                string JsonNetDiskList = Base.GlobalParams.NetDiskServiceSVC.GetListCTE(fids, "", "");
                List<Model.NetDisk> downloadNetDiskList = JsonConvert.DeserializeObject<List<Model.NetDisk>>(JsonNetDiskList);
                List<Model.NetDisk> netDiskList = (from c in downloadNetDiskList
                                                   where c.FID == decimal.Parse(fids)
                                                   select c).ToList();
                if (netDiskList.Count > 0)
                {
                    if (netDiskList[0].FType == "F")//如果是文件夹，创建文件夹
                    {
                        //下载完成之后返回下载后的绝对路径
                        string SrcPath = NetdiskDir + netDiskList[0].relPath;
                        string DestPath = path + "\\" + netDiskList[0].FName;
                        downloadFileClient.DownloadSingle(SrcPath, DestPath);
                        returnstrs.Add(DestPath);

                    }
                    if (netDiskList[0].FType == "D")//如果是文件夹，创建文件夹
                    {

                        string DestPath = path + "\\" + netDiskList[0].FName;
                        Common.serverIO.CreateDir(DestPath);
                        //List<Model.NetDisk> netDiskListfiles = (from c in downloadNetDiskList
                        //                                        where c.FParentID == decimal.Parse(netDiskList[0].FID.ToString())
                        //                                        select c).ToList();
                        //foreach (Model.NetDisk subfile in netDiskListfiles)
                        //{
                        //    string SrcPath = NetdiskDir + subfile.relPath;
                        //    string DestPath = path + "\\" + subfile.FName;
                        //    downloadFileClient.DownloadSingle(SrcPath, DestPath);
                        //    returnstrs.Add(DestPath);
                        //}
                        DownloadSubFiles(netDiskList[0].FID, DestPath, downloadNetDiskList);
                        returnstrs.Add(DestPath);
                    }
                }
            }
            return returnstrs;
        }
        /// <summary>
        /// 递归下载文件
        /// </summary>
        /// <param name="FID"></param>
        /// <param name="returnstrs"></param>
        /// <param name="downloadNetDiskList"></param>
        public void DownloadSubFiles(decimal FID, string FromPath, List<Model.NetDisk> downloadNetDiskList)
        {
            NetDisk.DownloadFileClient downloadFileClient = new NetDisk.DownloadFileClient();
            string NetdiskDir = Base.GlobalParams.NetDiskServiceSVC.GetNetDiskDir();
            string path = System.IO.Path.GetTempPath();
            List<Model.NetDisk> netDiskListfiles = (from c in downloadNetDiskList
                                                    where c.FParentID == decimal.Parse(FID.ToString())
                                                    select c).ToList();
            foreach (Model.NetDisk subfile in netDiskListfiles)
            {
                if (subfile.FType == "F")
                {

                    string SrcPath = NetdiskDir + subfile.relPath;
                    string DestPath = FromPath + "\\" + subfile.FName;
                    downloadFileClient.DownloadSingle(SrcPath, DestPath);
                    //returnstrs.Add(DestPath);

                }
                if (subfile.FType == "D")
                {

                    string DestPath = FromPath + "\\" + subfile.FName;
                    Common.serverIO.CreateDir(DestPath);
                    DownloadSubFiles(subfile.FID, DestPath, downloadNetDiskList);
                }
            }

        }
        /// <summary>
        /// 左边树形控件拖放完成事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tlstLeft_DragDrop(object sender, DragEventArgs e)
        {

            if (e.Data.GetDataPresent(DataFormats.Text))
            {
                //取text类型的返回对象
                string[] objData = e.Data.GetData(DataFormats.Text) as string[];
                // object downloadpath = (System.Array)e.Data.GetData(DataFormats.FileDrop);
                string[] patha = objData as string[];
                string ids = "";
                foreach (string item in patha)
                {
                    ids += item + ",";
                }
                //得到对应的id
                if (ids == "")
                {
                    XtraMessageBox.Show("请选择需要移动的文件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                }
                else
                {
                    TreeListHitInfo hi = tlstLeft.CalcHitInfo(tlstLeft.PointToClient(new Point(e.X, e.Y)));
                    string fid = hi.Node.Tag.ToString();




                    decimal DestDirID = decimal.Parse(fid);

                    jsonMsg = Base.GlobalParams.NetDiskServiceSVC.MoveNetDisk(ids, DestDirID.ToString());
                    Common.GlobalUtil.GetJsonMsgResult(jsonMsg, out code, out msg);

                    if (code != "0")
                    {
                        XtraMessageBox.Show(msg, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    else
                    {
                        XtraMessageBox.Show("移动成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                        CurrentFID = DestDirID;
                        RefreshNetDisk();
                    }




                }
            }
        }

        private void tlstLeft_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.Text))
            {
                e.Effect = DragDropEffects.Move;
            }
        }


        #endregion

      























    }
}







//数据源接口对象
public class ShellDataObject : DataObject
{
    //下载委托
    public delegate List<string> DownloadFid(string[] fids);
    public DownloadFid onDownloadFid;
    //保存已下载的路径字典类型节省系统资源
    private Dictionary<List<string>, List<string>> hasdownloadedstrs = new Dictionary<List<string>, List<string>>();

    /// <summary>
    /// 重写提取数据函数
    /// </summary>
    /// <param name="format"></param>
    /// <returns></returns>
    public override object GetData(String format)
    {
        if (format == DataFormats.FileDrop)
        {
            Object obj = base.GetData(DataFormats.FileDrop);
            string[] fromstrs = obj as string[];

            //如果未下载执行下载
            if (hasdownloadedstrs.ToList().SelectMany(h => h.Key).Intersect(new List<string>(fromstrs)).ToList().Count == 0)
            {
                // GlobalParams.isshow = true;
                //旧的方法
                              //  string[] strs = this.onDownloadFid(fromstrs).ToArray();
                //下载完成添加纪录
                hasdownloadedstrs.Add(new List<string>(fromstrs), new List<string>(fromstrs));
                //  GlobalParams.isshow = false;
                return fromstrs;
            }
            else
            {
                //如果已下载方法保存过的记录
                string[] strout = hasdownloadedstrs.Where(h => h.Key.Any(y => (new List<string>(fromstrs)).Contains(y))).FirstOrDefault().Value.ToArray();
                return strout;
            }




        }
        else
        {
            Object obj = base.GetData(DataFormats.Text);
            return obj;
        }


    }
}











